【问题标题】:Interpreting json as string, how can I interpretate it as json? [duplicate]将 json 解释为字符串,如何将其解释为 json? [复制]
【发布时间】:2020-09-14 15:41:40
【问题描述】:

我有一个任务要处理文件 https://github.com/mledoze/countries/blob/master/countries.json ,它非常大。首先,我使用wget 下载它并尝试使用 0 元素:

import wget

print('Beginning file download with wget module')

url = 'https://raw.githubusercontent.com/mledoze/countries/master/countries.json'
wget.download(url, 'сountries.json')

handle = open("сountries.json", "r")
data = handle.read()
print(data[0])
handle.close()

但是,整个 json 文件被识别为“str”,并且作为 0 元素我只收到“[”我该如何解决这个问题?

【问题讨论】:

  • 也许您的意思是使用内置的json 模块将字符串解码为列表。
  • 是的,JSON 一个字符串。从任何文件中读取,您总是会读取字符串。您永远不会直接从文件中读取对象。您必须使用 json.load 解码 JSON。

标签: python json python-3.x


【解决方案1】:

data 是一个字符串。您必须首先将其解码为(显然)一个列表。

import json


with open("countries.json") as handle:
    data = json.load(handle)
    print(data[0])

【讨论】:

  • FileNotFoundError: [Errno 2] No such file or directory: 'countries.json',但我清楚地看到在工作项目文件夹中有一个文件“countries.json”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2013-05-26
  • 2019-05-18
  • 2017-06-03
相关资源
最近更新 更多