Python对JSON数据的解析,什么是大数据分析,1.python与j


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 jsondata = [    {        "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)

Python对JSON数据的解析

评论关闭