Python json转储抛出错误,因为"不是JSON可序列化的""

时间:2014-11-08 21:11:29

标签: python json

我正在尝试加载一个简单的json,即

[
  {
    "positions": [
      {
        "title": "a",
        "is-current": true,
        "company-name": "a"
      }
    ],
    "public-profile-url": "\/pub\/ademar-b\/20\/22b\/842",
    "location": "Irati Area, Brazil",
    "first-name": "Ademar",
    "num-connections": "4",
    "last-name": "B",
    "industry": "Government Administration"
  },
  {
    "positions": [
      {
        "title": "Messenger",
        "is-current": true,
        "company-name": "YAA Croup"
      },
      {
        "title": "Messenger",
        "is-current": true,
        "company-name": "YAA Croup"
      }
    ],
    "public-profile-url": "\/pub\/adememb-b\/41\/7a8\/171",
    "location": "Ethiopia",
    "first-name": "adememb",
    "num-connections": "0",
    "last-name": "B",
    "industry": "Wholesale"
  }
]

我的任务是加载json,清理一些条目然后将其转储到文件中。但我的以下简单代码给出了错误:

    profiles=json.load(fin)
    json.dumps(outfile,profiles)

我无法理解为什么这个简单的东西不起作用,我只是加载并转储相同的json?

编辑:

我也遇到了与json.dump()函数相同的错误。

1 个答案:

答案 0 :(得分:4)

你使用了错误的功能;您正试图将文件对象转换为JSON字符串:

>>> json.dumps(open('/tmp/demo.json', 'w'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <open file '/tmp/demo.json', mode 'w' at 0x1006576f0> is not JSON serializable

您想在此使用json.dump()(无s),但是:

json.dump(profiles, outfile)

首先是序列化的对象,文件对象是第二个。