Python 解析 json

python解析json文件#

什么是json文件
定义:(可以直接看官网:http://json.org/

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON 语法是 JavaScript 对象表示语法的子集。

基本数据格式:

  1. 对象,{key1:value2,key2:value2}
  2. 数组,[item1,item2,item3]

DEMO:javascript和python中的使用方法
最基本的key/value,单个

demo = {"key":"value"}
[js] -- demo.key
[python] -- demo["key"]

当多个的key/value时,应该如下表示:

demo = {"key1":"value1","key2":"value2","key3":"value3"}
[js] -- demo.key1
[python] -- demo["key1"]

当value不是单个值,是一串key/value

demo = {"key1":{"key11":"value11","key12":"value12","key13":"value13"}}
[js] -- demo.key1.key11
[python] -- demo["key1"]["key11"]

当value是数组

demo = {"key1":[{"key11":"value11","key12":"value12","key13":"value13"},{"key21":"value21","key22":"value22","key23":"value23"}]}
[js] -- demo.key1[1].key21
[python] -- demo["key1"][1]["key21"]

实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接转换成定义它的代码的字符串。python里面有一个simplesjon的库,可以方便的完成json的生成和解析。可以参考官网文档:http://simplejson.github.io/simplejson/

主要的函数

dump, 将python字典转化成json文件对象
dumps,将python字典转化成json字符串
load, 将json文件对象转为成python字典
loads,将json字符串转为python字典

使用的简单demo

$ cat test.json 
{"key1":[{"key11":"value11","key12":"value12","key13":"value13"},{"key21":"value21","key22":"value22","key23":"value23"}]}

$ cat json.py 

import simplejson as json

f = file("test.json")
s1 = json.load(f)
print s1["key1"][1]["key21"]
f.close

s2 = json.loads('{"key1":[{"key11":"value11","key12":"value12","key13":"value13"},{"key21":"value21","key22":"value22","key23":"value23"}]}')
print s2["key1"][1]["key21"]

$ python json.py 
value21
value21
原文地址:https://www.cnblogs.com/zk47/p/3930296.html