逐行读取json文件

时间:2014-11-26 18:16:01

标签: python json

我有一个json文件

{
  "rows": [
    {
     "votes": {
     "funny": 0, 
     "useful": 1, 
     "cool": 0
     }, 
     "user_id": "zvNimI98mrmhgNOOrzOiGg", 
      "review_id": "I7Kte2FwXWPCwdm7ispu1A", 
      "text": "Pretty good dinner with a nice selection of food"

      },
      {
      "votes": {
      "funny": 2, 
       "useful": 5, 
       "cool": 0
     }, 
      "user_id": "Au3Qs-AAZEWu2_4gIMwRgw", 
      "review_id": "SSlO5u2nIJ8PoAKAgN5m3Q", 
      "text": "Yeah, thats right a five freakin star rating."
    }
  ]
}

我只想逐个阅读"text",即我想访问第一个"text",对其进行一些操作,然后转到下一个"text"

2 个答案:

答案 0 :(得分:2)

您可以像在dict中一样访问数据,因为您当前的json数据已经是一个:

>>> text = """{
  "rows": [
    {
     "votes": {
     "funny": 0, 
     "useful": 1, 
     "cool": 0
     }, 
     "user_id": "zvNimI98mrmhgNOOrzOiGg", 
      "review_id": "I7Kte2FwXWPCwdm7ispu1A", 
      "text": "Pretty good dinner with a nice selection of food"

      },
      {
      "votes": {
      "funny": 2, 
       "useful": 5, 
       "cool": 0
     }, 
      "user_id": "Au3Qs-AAZEWu2_4gIMwRgw", 
      "review_id": "SSlO5u2nIJ8PoAKAgN5m3Q", 
      "text": "Yeah, thats right a five freakin star rating."
    }
  ]
}"""

假设上面是你的json文本,(可以用简单的方法获得) with open("json_file.txt", "r") as f: text = f.read(),您现在可以使用

将json转换为字典格式
>>> import json
>>> json_data = json.loads(text)

要访问数据,您现在可以像在字典上一样正常操作。

因此,在列表理解中,这变为:

>>> print [d["text"] for d in json_data["rows"]]
['Pretty good dinner with a nice selection of food',
 'Yeah, thats right a five freakin star rating.']

在循环中,这变为

>>> for d in json_data["rows"]:
...     print d["text"]

Pretty good dinner with a nice selection of food
Yeah, thats right a five freakin star rating.

请注意,json不是逐行读取的,它是完整转换的,只有这样才能访问所需的字段。

答案 1 :(得分:1)

打开一个文件,将内容读作JSON,然后迭代你得到的数据是一件简单的事情:

import json
with open("my_data.json") as my_data_file:
    my_data = json.load(my_data_file)

for row in my_data["rows"]:
    do_something(row["text"])