【问题标题】:TypeError: ... is not JSON serializable error when adding new values to an object by PythonTypeError: ... is not JSON serializable error when added new values to an object by Python
【发布时间】:2015-11-26 00:58:23
【问题描述】:

我有这样一个json对象:

{
     "people":[
        {"firstName":"Hasan Sait", "lastName":"Arslan", "email":"hasan.sait.arslan@gmail.com"}]
}

我想通过 python 为这个 json 对象添加新值,如下所示:

import json

with open('data.json', 'r+') as json_file:
        json_data = json.load(json_file)
        people = json_data['people']
        people.append({"firstName":"Mehmet"})
        json_file.seek(0, 0)
        json.dump(json_file, json_data)
        json_file.truncate()

我收到以下错误:TypeError: <open file 'data.json', mode 'r+' at 0x7f3f85a4b5d0> is not JSON serializable

在 stackoverflow 中,我之前曾问过类似的问题,但我找不到任何有益的解决方案。

你能告诉我哪里错了吗?

【问题讨论】:

  • 您的json 无效。 "email":"hasan.sait.arslan@gmail.com"]}这部分应该是"email":"hasan.sait.arslan@gmail.com"}]
  • 谢谢。问题不在于。这只是我写问题时的打字错误。

标签: python json serialization


【解决方案1】:

json.dumps 不写入流,它只是获取对象并返回 JSON 序列化字符串。然后,您可以将其保存到文件中。

import json

with open('data.json', 'r+') as json_file:
      json_data = json.load(json_file)
      people = json_data['people']
      people.append({"firstName":"Mehmet"})
      json_file.seek(0, 0)
      jsonString = json.dumps(json_data)
      json_file.write(jsonString)
      json_file.truncate()

【讨论】:

    【解决方案2】:

    你刚刚弄错了json_file和json_data的顺序,所以它告诉你不能把filepointer当作json来使用。使用 json.dump 时,对象在前,文件指针在后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 2019-05-06
      • 2019-10-09
      • 2021-03-02
      相关资源
      最近更新 更多