python 讀取 json文件

  • 本文是碎片知識

本文用的是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.

發佈了105 篇原創文章 · 獲贊 159 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章