【问题标题】:JSON Line issue when loading from import.io using Python使用 Python 从 import.io 加载时出现 JSON 行问题
【发布时间】:2016-11-29 10:05:07
【问题描述】:

我很难将 API 响应从 import.io 加载到文件或列表中。

我使用的端点是https://data.import.io/extractor/{0}/json/latest?_apikey={1}

以前我的所有脚本都设置为使用普通 JSON 并且一切运行良好,但现在他们决定使用 json 行,但不知何故它似乎格式不正确。

我尝试调整脚本的方式是通过以下方式读取 API 响应:

url_call = 'https://data.import.io/extractor/{0}/json/latest?_apikey={1}'.format(extractors_row_dict['id'], auth_key)
r = requests.get(url_call)

with open(temporary_json_file_path, 'w') as outfile:
    json.dump(r.content, outfile)

data = []
with open(temporary_json_file_path) as f:
    for line in f:
        data.append(json.loads(line))

这样做的问题是,当我检查 data[0] 时,所有的 json 文件内容都被转储到其中...

data[1] = IndexError: list index out of range

这里是data[0][:300]的例子:

u'{"url":"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de","result":{"extractorData":{"url":"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de","resourceId":"23455234","data":[{"group":[{"Brand":[{"text":"Brand","href":"https://www.example.com'

有人对此 API 的响应有经验吗? 除了这个,我从其他来源读取的所有其他 jsonline 都可以正常工作。

根据评论编辑:

print repr(open(temporary_json_file_path).read(300))

给出这个:

'"{\\"url\\":\\"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de\\",\\"result\\":{\\"extractorData\\":{\\"url\\":\\"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de\\",\\"resourceId\\":\\"df8de15cede2e96fce5fe7e77180e848\\",\\"data\\":[{\\"group\\":[{\\"Brand\\":[{\\"text\\":\\"Bra'

【问题讨论】:

  • 等等,什么?您的输出看起来像是您(或他们)添加了 API 内容的 repr(),因此 JSON 行编码为 Python 文字。 print repr(open(temporary_json_file_path).read(300)) 长什么样子?
  • 对问题添加了编辑
  • 是的,数据是双重编码的。这看起来像是 import.io 方面的错误。他们的抓取是如何工作的?你会写一些代码吗?如果是这样,请不要在他们这边编码为 JSON,因为看起来输出是自动 JSON 编码的。
  • 您现在必须再次在内容上使用json.loads() 来解开双重编码,但最好不要编码两次。
  • 不,这是 API 的原始输出,我会尝试双重展开并检查它是否有效,否则我会尝试自己编写一个快速解码器。谢谢!

标签: python json import.io jsonlines


【解决方案1】:

您的代码中存在双重编码错误:

with open(temporary_json_file_path, 'w') as outfile:
    json.dump(r.content, outfile)

试试:

with open(temporary_json_file_path, 'w') as outfile:
    outfile.write(r.content)

【讨论】:

  • 我不知道我是怎么错过的。我删除了我的错误答案。
  • 让我试一试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
相关资源
最近更新 更多