gpt4 book ai didi

Python json 转储将错误抛出为 "is not JSON serializable"“

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:44 25 4
gpt4 key购买 nike

我正在尝试加载一个简单的 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 字符串:

>>> 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)

首先要序列化的对象,其次是文件对象。

关于Python json 转储将错误抛出为 "is not JSON serializable"“,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26822133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com