JSON格式在python 中的使用。
JSON (JavaScript Object Notation) is a popular data format used for representing structured data. It’s common to transmit and receive data between a server and web application in JSON format.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
{
"firstName": "Jane",
"lastName": "Doe",
"hobbies": ["running", "sky diving", "singing"],
"age": 35,
"children": [
{
"firstName": "Alice",
"age": 6
},
{
"firstName": "Bob",
"age": 8
}
]
}
|
JSON 主要有两种数据结构:
- 由 key-value对组成的数据结构。这种数据结构在不同的语言中有不同的实现。例如在 Python中是一种 dict 对象;在C语言中是一个struct;在其他语言中,则可能是 record等。
- 有序集合。这种数据结构在 Python 中对应于列表;在其他语言中,可能对应于 list等。
python JSON to dict
(注意使用string 类型表示 JSON 的方式,使用单引号,双引号,三个引号 区分不同)
1
2
3
4
5
6
7
8
9
10
|
import json
person = '{"name": "Bob", "languages": ["English", "Fench"]}'
person_dict = json.loads(person)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
print( person_dict)
# Output: ['English', 'French']
print(person_dict['languages'])
|
1
2
3
4
5
6
7
8
9
|
import json
person_dict = {'name': 'Bob',
'age': 12,
'children': None
}
person_json = json.dumps(person_dict)
# Output: {"name": "Bob", "age": 12, "children": null}
print(person_json)
|
还有一种写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
my_json_string = """{
"article": [
{
"id":"01",
"language": "JSON",
"edition": "first",
"author": "Derrick Mwiti"
},
{
"id":"02",
"language": "Python",
"edition": "second",
"author": "Derrick Mwiti"
}
],
"blog":[
{
"name": "Datacamp",
"URL":"datacamp.com"
}
]
}
"""
to_python = json.loads(my_json_string)
|
1
2
3
|
to_python['blog']
# [{'URL': 'datacamp.com', 'name': 'Datacamp'}]
|
Python Tuple to JSON Array
1
2
3
|
tuple_example = 'Mango', 'Banana', 'Apple';
print(json.dumps(tuple_example));
# ["Mango", "Banana", "Apple"]
|
Converting JSON to Python Objects
We can parse the above JSON string using json.loads() method from the json module. The result is a Python dictionary.
Converting Python Objects to JSON
Using json.dumps() we can convert Python Objects to JSON.
json.load vs json.loads
json.load is used when loading a file while json.loads(load string) is used when loading a string.
json.dump vs json.dumps
We use json.dump when we want to dump JSON into a file. json.dumps(dump string) is used when we need the JSON data as a string for parsing or printing.
json.dump()方法将JSON写入文件。
1
2
3
4
5
6
7
8
9
10
|
import json
person_dict = {"name": "Bob",
"languages": ["English", "Fench"],
"married": True,
"age": 32
}
with open('person.txt', 'w') as json_file:
json.dump(person_dict, json_file)
|
1
2
3
4
5
6
7
|
import json
with open('person.json') as f:
data = json.load(f)
# Output: {'languages': ['English', 'Fench'], 'name': 'http://china-testing.github.io/'}
print(data)
|
Format the Result
The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.
The json.dumps() method has parameters to make it easier to read the result:
You can also define the separators, default value is (", “, “: “), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values:
1
2
3
|
# default choice
json.dumps(x)
|
格式更加可读
1
|
json.dumps(x, indent=4)
|
修改了默认的分割符
1
|
json.dumps(x, indent=4, separators=(". ", " = "))
|
python 格式和json 格式的相互转换
| Python |
JSON |
| dict |
Object |
| list |
Array |
| tuple |
Array |
| str |
String |
| int |
Number |
| float |
Number |
| True |
true |
| False |
false |
| None |
null |
1
2
3
|
boolean_value = False
print(json.dumps(boolean_value))
# false
|
JSON in APIs
Flask provides the jsonify module that will enable us to achieve this.
1
2
3
4
5
6
7
|
from flask import jsonify
@app.route('/_get_current_user')
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
|