Python對JSON數據的解析


1.python與json數據結構的對應情況

   

2.dumps:卸載,將json對象卸載為str

*sort_keys:排序

*indent:格式化

*ensure_ascii參數,想要輸出中文時,要設置ensure_ascii=False

*skipkeys參數,在encoding過程中,dict對象的key只可以是string對象,如果是其他類型,那么在編碼過程中就會拋出ValueError的異常。skipkeys可以跳過那些非string對象當作key的處理

def 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):
"""Serialize ``obj`` to a JSON formatted ``str``.

# cached encoder
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
default is None and not sort_keys and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, default=default, sort_keys=sort_keys,
**kw).encode(obj)

     loads:裝載,將str對象裝載為json

def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``s`` (a ``str`` instance containing a JSON
document) to a Python object.

if not isinstance(s, str):
raise TypeError('the JSON object must be str, not {!r}'.format(
s.__class__.__name__))
if s.startswith(u'\ufeff'):
raise ValueError("Unexpected UTF-8 BOM (decode using utf-8-sig)")
if (cls is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and object_pairs_hook is None and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if object_pairs_hook is not None:
kw['object_pairs_hook'] = object_pairs_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
return cls(**kw).decode(s)

demo:

import json
data = [
    {
        "school":"middle",
        "name":"smith",
        "age":22
    },
    "icecream",22,None,True, False,2.12,[4,31,"call"]
]
res = json.dumps(data)
dict_data = json.loads(res)

3.dump,load,文件操作

# 寫入 JSON 數據
with open('data.json', 'w') as f:
    json.dump(data, f)
 
# 讀取數據
with open('data.json', 'r') as f:
    data = json.load(f)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM