#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
"""
python对象转json字符串
"""
# 构造字典
python2json = {}
# 构造list
listTest = [1,2,3]
python2json["listTest"] = listTest
python2json["strData"] = "Python object to json."
# 转换成json字符串
jsonStr = json.dumps(python2json)
print(jsonstr)
结果:
{"listTest": [1, 2, 3], "strData": "Python object to json."}
示例2:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
"""
python对象转json字符串
"""
# 构造字典
python2json = {}
# 构造dict
dictData = {'a': 123, 'b': [3,4,5], 'c': (4,5,6)}
python2json["dictTest"] = dictData
# 转换成json字符串
jsonStr = json.dumps(python2json)
print(jsonStr)
结果:
{"dictTest": {"a": 123, "b": [3, 4, 5], "c": [4, 5, 6]}}
4.json转python对象主要使用的函数是:json.loads()。例如:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
"""
json转python对象
"""
str = '{"Data1": [1, 2, 3], "Data2": "Json to python object."}'
json2python = json.loads(str)
print(json2python)
结果:
{'Data1': [1, 2, 3], 'Data2': 'Json to python object.'}
5.json编码的格式几乎和python语法一致,不同点在于True会被映射为true,False会被映射为false,None会被映射为null,元组()会被映射为列表[]。
6.json使用说明文档参考地址:https://docs.python.org/2/library/json.html