标签:使用 load height table body 类型 one default tab
函数 | 描述 |
json.dumps | 将 Python 对象编码成 JSON 字符串 |
json.loads | 将已编码的 JSON 字符串解码为 Python 对象 |
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True,
cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
#!/usr/bin/python3 import json data = [ { ‘a‘ : 1, ‘b‘ : 2, ‘c‘ : 3, ‘d‘ : 4, ‘e‘ : 5 } ] json = json.dumps(data) print (json)
以上代码执行结果为:
[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]
使用参数让 JSON 数据格式化输出:
>>> import json >>> print json.dumps({‘a‘: ‘Runoob‘, ‘b‘: 7}, sort_keys=True, indent=4, separators=(‘,‘, ‘: ‘)) { "a": "Runoob", "b": 7 }
python 原始类型向 json 类型的转化对照表:
Python | JSON |
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
dump (obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None,
separators=None, encoding=‘utf-8‘, default=None, sort_keys=False, **kw)
实例
import json name_emb = {"key1":"value1","key2":"value2"} emb_filename=r‘E:\learning\auto\python\emb_json.json‘ json.dump(name_emb,open(emb_filename,‘w‘))
以上代码执行结果为:
{"key1": "value1", "key2": "value2"}
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
#!/usr/bin/python3 import json jsonData = ‘{"a":1,"b":2,"c":3,"d":4,"e":5}‘; text = json.loads(jsonData) print (text)
以上代码执行结果为:
{u‘a‘: 1, u‘c‘: 3, u‘b‘: 2, u‘e‘: 5, u‘d‘: 4}
json 类型转换到 python 的类型对照表:
JSON | Python |
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
load (fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None,
parse_constant=None, object_pairs_hook=None, **kw)
import json emb_filename=r‘E:\learning\auto\python\emb_json.json‘ js_Obj = json.load(open(emb_filename,‘r‘)) print(js_Obj) print(type(js_Obj)) for key in js_Obj.keys(): print(‘key:%s value: %s‘ %(key,js_Obj.get(key)))
以上代码执行结果为:
{‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘} <class ‘dict‘> key:key1 value: value1 key:key2 value: value2
标签:使用 load height table body 类型 one default tab
原文地址:https://www.cnblogs.com/huhu-xiaomaomi/p/10340853.html