使用键作为数字处理特殊 JSON



我想通过json.loads将数据从文件提取到字典中。例:

{725: 'pitcher, ewer',
726: "plane, carpenter's plane, woodworking plane"}
  1. json.loads无法将键作为数字处理
  2. 有些
  3. 值是",有些是'。

有什么建议吗?

法典

import requests
url = url
r = requests.get(url)
response = r.text.replace('n','')
response = re.sub(r':(d+):*', r'"1"', response)

您提供的文件似乎是有效的 Python dict,所以我建议使用另一种方法,使用 literal_eval .

from ast import literal_eval
data = literal_eval(r.text)
print(data[726])

输出:plane, carpenter's plane, woodworking plane


如果您仍然喜欢 json ,那么您可以尝试使用正则表达式将数字替换为字符串。

import re
s = re.sub(r"(?m)^(W*)(d+)b", r'1"2"', r.text)
data = json.loads(s)

最新更新