读取包含多个JSON对象的文件(python)
我已经根据我的谷歌搜索API结果创建了一个JSON文件。我正在尝试读取文件并解析对象 每个搜索结果都是一个JSON数组,如下所示。我在一个JSON文件中有200个这样的数组读取包含多个JSON对象的文件(python),python,json,python-3.x,Python,Json,Python 3.x,我已经根据我的谷歌搜索API结果创建了一个JSON文件。我正在尝试读取文件并解析对象 每个搜索结果都是一个JSON数组,如下所示。我在一个JSON文件中有200个这样的数组 { "kind": "customsearch#result", "title": "text here", "htmlTitle": "text here", "link": "link here", "displayLink": "text here", "snippet": "text here
{
"kind": "customsearch#result",
"title": "text here",
"htmlTitle": "text here",
"link": "link here",
"displayLink": "text here",
"snippet": "text here",
"htmlSnippet": "text here",
"cacheId": "ID string",
"formattedUrl": "text here",
"htmlFormattedUrl": "link here",
"pagemap": {
"metatags": [
{
"viewport": "width=device-width, initial-scale=1"
}
],
"Breadcrumb": [
{
"title": "text here",
"url": "link here",
},
{
"title": "text here",
"url": "link here",
},
{
"title": "text here",
"url": "link here",
},
{
"title": "text here",
"url": "link here",
}
]
}
我在将JSON文件读入JSON.load时遇到问题
如何读取此文件并开始解析项目
def ingest_json(input):
try:
with open(input, 'r', encoding='UTF-8') as f:
json_data = json.loads(f)
except Exception:
print(traceback.format_exc())
sys.exit(1)
抛出此错误:
TypeError: the JSON object must be str,
bytes or bytearray, not 'TextIOWrapper'
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 269
column 2 (char 10330)
抛出此错误:
TypeError: the JSON object must be str,
bytes or bytearray, not 'TextIOWrapper'
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 269
column 2 (char 10330)
在json.loads()
中,'s'代表字符串,因此它仅适用于字符串类型
json.load()
无疑是您想要的方法,尽管它非常特别地要求json格式良好,并且根据规范,单个json文件只能包含一个json对象
尝试将数据拆分为多个文件,每个文件都有一个对象,或者在解析之前在python中按对象拆分字符串。另外,请检查是否处理尾部逗号问题。第一个代码:使用
load
而不是loads
您的json无效,使用来验证您的json是否正确,例如:“url”:“link here”,}
如果逗号不正确,请将其删除。可能重复的