简体   繁体   English

Python json转储引发错误,因为“不是JSON可序列化的”

[英]Python json dumps throws error as “is not JSON serializable”"

I am trying to load a simple json which is, 我正在尝试加载一个简单的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"
  }
]

My task is to load the json, clean some entries and then dump it to file. 我的任务是加载json,清理一些条目,然后将其转储到文件中。 But my following simple code is giving error: 但是我下面的简单代码给出了错误:

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

I am not able to understand as why this simple thing is not working, where I am just loading and dumping same json? 我不明白为什么这个简单的东西不起作用,我只是在其中加载和转储相同的json?

EDIT: 编辑:

I am getting same error with json.dump() function also. 我在json.dump()函数中也遇到了相同的错误。

You are using the wrong function; 您使用了错误的功能; you are trying to turn the file object into a JSON string: 您正在尝试将文件对象转换为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

You want to use json.dump() here (no s ), but : 您想在这里使用json.dump() (no s ),但是:

json.dump(profiles, outfile)

The object to serialise comes first, the file object second. 要序列化对象首先出现,第二个是文件对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM