简体   繁体   English

OSError:[Errno 63] JSON 文件(python)中的文件名太长

[英]OSError: [Errno 63] File name too long in JSON FILE (python)

i have this error - OSError: [Errno 63] File name too long:我有这个错误 - OSError: [Errno 63] 文件名太长:

what is the best way to work around this?解决此问题的最佳方法是什么?

import requests
import json
import codecs

url = 'https://ratings.food.gov.uk/OpenDataFiles/FHRS314en-GB.json'
response = requests.get(url)

text = response.text

data = json.load(codecs.open(text, encoding='utf8'))

print('data', data)

You could just leave out the first 3 Bytes, which indicate the BOM:您可以省略前 3 个字节,它们表示 BOM:

import requests
import json

url = 'https://ratings.food.gov.uk/OpenDataFiles/FHRS314en-GB.json'
response = requests.get(url)

text = response.content[3:]
data = json.loads(text)
print(data)

More dynamically would to lookup the correct BOM and strip if off the data:更动态地查找正确的 BOM 并删除数据:

BOMS = [
    codecs.BOM,
    codecs.BOM_BE,
    codecs.BOM_LE,
    codecs.BOM_UTF8,
    codecs.BOM_UTF16,
    codecs.BOM_UTF16_BE,
    codecs.BOM_UTF16_LE,
    codecs.BOM_UTF32,
    codecs.BOM_UTF32_BE,
    codecs.BOM_UTF32_LE,
]

url = 'https://ratings.food.gov.uk/OpenDataFiles/FHRS314en-GB.json'
response = requests.get(url)
data = response.content

for BOM in BOMS:
    if data.startswith(BOM):
        data = json.loads(data[len(BOM):])
        break
print(data)

Out:出去:

{'FHRSEstablishment': {'Header': ...

codecs.open is used to open files. codecs.open用于打开文件。 You used the entirety of the website's JSON response as that file name.您使用了整个网站的 JSON 响应作为该文件名。 requests already knows about JSON and you can just have it do the decode for you requests已经知道 JSON 并且您可以让它为您解码

import requests
import json
import codecs

url = 'https://ratings.food.gov.uk/OpenDataFiles/FHRS314en-GB.json'
response = requests.get(url)
data = response.json()
print('data', data)

This is far better than making some unwarranted assumptions about how the JSON from this particular web site is encoded.这比对来自这个特定 web 站点的 JSON 的编码方式做出一些毫无根据的假设要好得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM