JavaScript Object Notation:是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。Json是带有格式的字符串,主要用于数据交换,即程序和程序之间的信息互传,使用Json会更加方便。Json主要由2种结构:Json对象和Json数组。
{
"key": value,
"key": value
}
其中:
key必须是字符串
value可以是:
数字
字符串
列表
Json对象或Json数组
Json数组可以简单理解成Python中的列表套多个字典:[{}, {}, {}], Json对象:Python字典
Json对象:
{
"age": 11,
"name": "周杰伦",
"hobby": ["唱","跳","rap"],
"other": {
"身高":172,
"体重":68
}
}
Json数组:
[
{"name": "周杰伦", "age":11},
{"name": "蔡依林", "age":12},
{"name": "小明", "age":16}
]
Python中使用Json:
import json
d = {
"name": "Alice",
"age": 30,
"city": "New York"
}
s = json.dumps(d, ensure_ascii=False)
print(str(d), type(d))
print(s, type(s))
l = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Los Angeles"},
{"name": "Charlie", "age": 35, "city": "Chicago"}
]
t = json.dumps(l, ensure_ascii=False)
print(str(l), type(l))
print(t, type(t))
jsonStr = '{"name": "Alice", "age": 30, "city": "New York"}'
jsonArrayStr = '[{"name": "Alice", "age": 30, "city": "New York"},{"name": "Bob", "age": 25, "city": "Los Angeles"},{"name": "Charlie", "age": 35, "city": "Chicago"}]'
p = json.loads(jsonStr)
print(p, type(p))
q = json.loads(jsonArrayStr)
print(q, type(q))