为什么我不能用python加载这个json文件?

2024-04-28 20:31:36 发布

您现在位置:Python中文网/ 问答频道 /正文

解决方案,如果有人在谷歌搜索时发现:
问题不在于代码本身,而在于Firefox上的下载。显然(参见https://bugzilla.mozilla.org/show_bug.cgi?id=1470011)有些服务器会将gzip文件复制两次。然后,下载的文件应称为file.json.gz.gz,但缺少一个.gz。需要提取两次才能获取内容


我正在尝试整理此文件中的一些信息:https://dl.vndb.org/dump/vndb-tags-latest.json.gz 我对使用json也很陌生,但我找不到任何对我有帮助的东西

问题是我无法将其加载到python中。使用7zip提取.gz文件并尝试使用json.load(open('vndb-tags-2020-12-31.json', encoding='utf-8'))加载该文件将返回错误

>>> UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

如果没有utf-8参数,我会

>>> UnicodeDecodeError: 'cp932' codec can't decode byte 0x8b in position 1: illegal multibyte sequence

相反。当我尝试使用gzip包在移动中解密文件时,我遇到了同样的问题

import gzip
with gzip.open('vndb-tags-2020-12-31.json.gz') as fd:
    json.load(fd)
>>> UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

我想我需要一个不同的编码选项,但是utf-16和32不起作用,我在帮助页面https://vndb.org/d14上找不到任何东西


Tags: 文件inhttpsorgjsontagsbytecan
1条回答
网友
1楼 · 发布于 2024-04-28 20:31:36

您可以下载、提取和加载json格式的数据

  1. 向目标url发送请求,并将数据捕获为字节对象
  2. 将其数据加载并保留在带有io模块的存储单元上
  3. 将io对象传递给gzip函数,并将其提取为json数据
  4. 将json字符串传递给dump属性,并将其保留为python字典

试试这个:

import requests, io, gzip, json


url = 'https://dl.vndb.org/dump/vndb-tags-latest.json.gz'
file_object = io.BytesIO(requests.get(url).content)

with gzip.open(file_object, 'r') as gzip_file:
    reserve_data = gzip_file.read()

load_json = json.loads(reserve_data)
beautiful_json = json.dumps(load_json, sort_keys=True, indent=4)
print(beautiful_json)

对于较大的文件,最好将gzip保存在磁盘上,然后从磁盘加载:

import requests, gzip, json

target_url = 'https://dl.vndb.org/dump/vndb-tags-latest.json.gz'
downloaded_gzip_file = requests.get(target_url).content

with open("my_json_file.gz", "wb") as gz_file:
    gz_file.write(downloaded_gzip_file)

with gzip.open("my_json_file.gz") as gz_file:
    load_json_data = json.load(gz_file)

beautiful_json = json.dumps(load_json_data, sort_keys=True, indent=4)
print(beautiful_json)

相关问题 更多 >