【问题标题】:Reading file that contains multiple JSON objects (python)读取包含多个 JSON 对象的文件(python)
【发布时间】:2019-01-31 20:09:22
【问题描述】:

我从我的 Google 搜索 API 结果创建了一个 JSON 文件。我正在尝试读取文件并解析对象。

每个搜索结果都是一个 JSON 数组,如下图所示。我在一个 JSON 文件中有 200 个这样的数组。

{
  "kind": "customsearch#result",
  "title": "text here",
  "htmlTitle": "text here",
  "link": "link here",
  "displayLink": "text here",
  "snippet": "text here",
  "htmlSnippet": "text here",
  "cacheId": "ID string",
  "formattedUrl": "text here",
  "htmlFormattedUrl": "link here",
  "pagemap": {
  "metatags": [
    {
      "viewport": "width=device-width, initial-scale=1"
    }
  ],
  "Breadcrumb": [
    {
      "title": "text here",
      "url": "link here",
    },
    {
      "title": "text here",
      "url": "link here",
    },
    {
      "title": "text here",
      "url": "link here",
    },
    {
      "title": "text here",
      "url": "link here",
    }
  ]
}

我在将 JSON 文件读入 json.load(s) 时遇到问题。

如何读取此文件并开始解析项目?

def ingest_json(input):
try:
    with open(input, 'r', encoding='UTF-8') as f:
        json_data = json.loads(f)
except Exception:
    print(traceback.format_exc())
    sys.exit(1)

抛出此错误:

TypeError: the JSON object must be str, 
bytes or bytearray, not 'TextIOWrapper'

def ingest_json(input):
try:
    with open(input, 'r', encoding='UTF-8') as f:
        json_data = json.load(f)
except Exception:
    print(traceback.format_exc())
    sys.exit(1)

抛出此错误:

 raise JSONDecodeError("Extra data", s, end)
                   json.decoder.JSONDecodeError: Extra data: line 269 
                   column 2 (char 10330)

【问题讨论】:

标签: python json python-3.x


【解决方案1】:

json.loads() 中,'s' 代表字符串,因此它仅适用于字符串类型。

json.load() 绝对是你想要的方法,虽然它对 json 的格式非常讲究,并且根据规范,单个 JSON 文件只能包含单个 JSON 对象。

尝试将数据拆分为多个文件,每个文件都有一个对象,或者在解析之前在 python 中按对象拆分字符串。另外,请查看 Can json.loads ignore trailing commas? 以处理尾随逗号问题。

【讨论】:

    猜你喜欢
    • 2021-03-03
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多