python的json速记
jshort的Python项目详细描述
jshort
python是json的简写。灵感来自q
这个包允许用很少的代码从json加载、转储到文件。
安装
pip install jshort
用法
# This is an instanceimportj# Loads json from file, stores it in data propertyh=j(input_path='/tmp/data.json')# Get datah.data#{# "foo": "bar"#}# Display colored contentprint(h)# orh.prt()# {# "oh": "dayum!"# }# The same, in short# For dataj(i='/tmp/data.json').d# Printj(i='/tmp/data.json').prt()# Write jsonj(output_path='/tmp/out.json',data={"foo":"bar"})# Also write data in a shorter way and change print content setting indentation to 2j(o='/tmp/out.json',d={"hey":"jude"},indent=2).prt()# {# "hey": "jude"# }# Traversing json documents using https://pypi.org/project/jsonpath-ng/j(d=my_dict).path('key')# Shorter and with more filteringj(d=my_dict).p('sub.*')# Or fintering on an array and from a filej(i='/tmp/data.json').p('key[1]')
有关json遍历的更多信息,请查看https://pypi.org/project/jsonpath-ng/。
如果筛选只返回一个结果,那么path方法只返回结果,否则它是一个结果列表。
json作为对象
可以将j实例中的json操作为python对象。尝试以下操作:
o=j(d={'a':{'b':1}}).obj#raw datao.data_#{'a': {'b': 1}}#pretty print itprint(o)#dumps with syntax coloration the json contento.c#Noneo.a#{'b': 1}o.a.b#1o.a['test']=1print(o.d_)#{'a': {'b': 1}, 'test': 1}
享受吧。