json与python
2022-09-26 本文已影响0人
呦丶耍脾气
Python 对象编码成 JSON 字符串
json.dumps
用于将 Python 对象编码成 JSON 字符串
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,allow_nan=True, cls=None, indent=None,separators=None,default=None, sort_keys=False, **kw)
import json
dict1 = {"name":"张三","age":10}
print(json.dumps(dict1)) #转json {"name": "\u5f20\u4e09", "age": 10}
str1 = '{"name":"张三","age":10}'
json1 = json.loads(str1)
print(json1) #{'name': '张三', 'age': 10}
print(json.dumps(dict1, sort_keys=True, indent=4))
'''
{
"age": 10,
"name": "\u5f20\u4e09"
}
'''
python 原始类型向 json 类型的转化对照表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
解码 JSON 数据
json.loads(s, *, cls=None, object_hook=None, parse_float=None,parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
import json
str1 = '{"name":"张三","age":10}'
json1 = json.loads(str1)
print(json1) #{'name': '张三', 'age': 10}
json 类型转换到 python 的类型对照表:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |