【发布时间】:2019-01-31 20:09:22
【问题描述】:
我从我的 Google 搜索 API 结果创建了一个 JSON 文件。我正在尝试读取文件并解析对象。
每个搜索结果都是一个 JSON 数组,如下图所示。我在一个 JSON 文件中有 200 个这样的数组。
{
"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(s) 时遇到问题。
如何读取此文件并开始解析项目?
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'
def ingest_json(input):
try:
with open(input, 'r', encoding='UTF-8') as f:
json_data = json.load(f)
except Exception:
print(traceback.format_exc())
sys.exit(1)
抛出此错误:
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 269
column 2 (char 10330)
【问题讨论】:
-
第一个代码:使用
load而不是loads -
你的json无效,使用jsonlint.com验证你的json是否正确,例如:
"url": "link here",}那个逗号不正确,去掉。
标签: python json python-3.x