如何在Python中从JSON文件中读取JSON对象数组

5
我有一个名为example.json的JSON文件,其中包含以下内容。
[{
 "product/productId" : "XXX",
  "product/title" : "14k Yellow Gold Butterfly Pendant, 16 ",
  "product/price" : "unknown",
  "review/userId" : "XXX",
  "review/profileName" : "Disappointed Sony customer",
  "review/helpfulness" : "1/1",
  "review/score" : "4.0",
  "review/time" : "1178150400",
  "review/summary" : "pretty necklace",
  "review/text" : "It is a nice made necklace, and the butterfly pendant looks beautiful. I love it.",
 "numOfPositive" : "2",
 "numOfNegative" : "0"
},
{ "product/productId" : "XXXX",
  "product/title" : "14k Yellow Gold Butterfly Pendant, 16 ",
  "product/price" : "unknown",
  "review/userId" : "TTT",
  "review/profileName" : "A. Thorpe  Amazon lover ",
  "review/helpfulness" : "1/1",
  "review/score" : "4.0",
  "review/time" : "1175990400",
  "review/summary" : "pretty necklace",
  "review/text" : "I bought this necklace on a whim; I love butterflies and it looked so dainty anadfasdfasdfd sweet. It was actually a little more weighty than I expected, although it's not a solid piece. The chain is shiny and nicer than I expected.",
 "numOfPositive" : "4",
 "numOfNegative" : "0"
}]

意思是,该文件包含许多由“,”分隔的文档。我该如何单独读取每个JSON文档并在Python中处理它(将其发送到REST API)?附注:原始文件可能有几GB的大尺寸。

1
这不是有效的JSON。它包含两个没有外部数组的对象。但这似乎是你的问题。谁制作了这个“JSON”文件? - user1907906
等等!你的输入是否包含[]对?你的问题是关于分割输入吗? - user1907906
它包含[]对。我该如何拆分数组中的每个对象? - Barak Schoster
1
如果输入是几个GB大小的一个文件,则使用像sed这样的外部工具将输入拆分成许多小文件。 - user1907906
1个回答

10

用任何文本编辑器打开文件,在文件的最开始添加一个[,在文件的末尾添加一个]。这将把您拥有的数据转换为有效的JSON数组。

然后使用json模块处理它。

import json
arr = json.loads("example.json")
# Do nifty stuff with resulting array.

8
loadS方法是用于字符串的,所以json.loads("example.json")会尝试解析字符串"example.json",而不是将其作为带有json扩展名的文件名进行解析。 - Chris Chiasson
3
同意@ChrisChiasson的观点,应该写成arr = json.load("example.json") - Hari
3
你不能将字符串传递给 json.load(..),它期望的第一个参数是一个文件对象。正确的方式是:with open("example.json", "r") as f: arr = json.load(f) - Martin Nowosad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接