您的位置:首页 > 编程语言 > Python开发

python 读取 json文件

2016-12-12 09:58 351 查看
本文是碎片知识

本文用的是
python 2.7


如果我又一个文件
1.json
内容如下:

{
"_id" : "318071578",
"avg_cost" : "",
"user_id" : "108781651",
"stars" : 5,
"content" : "够辣够麻 一直会光顾的 推荐!",
"shop_id" : "198191132",
"label_1" : {
"口味" : 4
},
"label_2" : {
"环境" : 4
},
"label_3" : {
"服务" : 4
},
"user_name" : "我想一想,",
"likes" : []
}


我可以直接这样用python读取,读取之后test是一个dict对象:

#coding=utf-8

import json

f = file('1.json')
test = json.load(f)
print test['_id']


但是一个json文件不可能只存储一条json数据吧,如果有多条json数据的话,我们就需要对原本的json文件进行一下简单的处理,处理成一个json数据的list,如下:

[
{
"_id" : "318071578",
... # other key-values
}
,
{
"_id" : "317717598",
... # other key-values
}
]


然后再读取json文件的代码如下:

#coding=utf-8

import json

f = file('1.json')
test = json.load(f)
for t in test:
print t['_id']


Ps: 这样的读取方法,json文件里面不能有任何注释

That`s all.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python json