python解析json文件
程序员文章站
2024-02-03 09:44:10
...
cat t.jo
{
"name":"test",
"type":"kkk",
"ppp":{"parate":[1,2]}
}
或者加个数组t2.jo:
[
{"name":"test","type":"kkk","ppp":{"parate":[1,2]}},
{"name":"ppp"}
]
2.解析t.jo
#python2.7
import json
In [61]: s=json.loads('{"name":"kkk","type":"ppp"}')
In [62]: s['name']
Out[62]: u'kkk'
-------------t.jo
f=file('t.jo')
s=json.load(file(f)) 或者 s=json.load(file("t.jo"))
print s['name']
print s[ppp]['parate'][0]
--------------t2.jo
In [97]: f=file('t2.jo').read()
In [98]: t=json.JSONDecoder().decode(f)
In [99]: print t[0]['ppp']
3.python3.X解析会有点变化(没有file函数了,用open代替):
#python 3.4.3
#cat k.json #一下为json文件的内容
{
"db":{
"ip":"127.0.0.1",
"port":3306
},
"web":{
"ip":"127.0.0.1",
"port":80
}
}
#---------------------------
#cat k.py
def jx_json():
print('你好!')
jsf=open(fls, 'r')
res=json.load(jsf)
#res=json.load(open(fls, 'r'))
print(res['db']['ip'])
print(res['db']['port'])
jsf.close()
if __name__ == "__main__":
jx_json()
#----------------------------
#python k.py
D:\Python34\python.exe E:/py/test/k.py
你好!
127.0.0.1
3306
转载于:https://my.oschina.net/jk409/blog/317751
上一篇: 电影解说类自媒体如何才能脱颖而出