gpt4 book ai didi

python - 在 python2.7 中将原始字符串转换为 JSON 对象

转载 作者:太空狗 更新时间:2023-10-30 00:29:30 30 4
gpt4 key购买 nike

我正在查询 PostgreSQL 服务器以获取数据,并且特定的 json 对象实际上作为字符串返回。我试过以下但它没有给出正确的输出:(它是 ipython 输出)

test
Out[103]: '{"max"=>28, "min"=>18, "custom"=>[{"id"=>"12345","name"=>"test_pur"}]}'
In[104]: test.replace("=>",":")
Out[104]: '{"max":28, "min":18, "custom":[{"id":"12345", "name":"test_pur"}]}'
In[105]: j_obj = json.dumps(test)
In[106]: j_obj
Out[106]: '"{\\"max\\"=>28, \\"min\\"=>18, \\"custom\\"=>[{\\"id\\"=>\\"12345\\", \\"name\\"=>\\"test_pur\\"}]}"'

如何通过识别“:”符号将字符串转换为json?

当我尝试“json.loads”时。以下是错误:

Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/IPython/core/interactiveshell.py", line 3035, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-12-a7562191decf>", line 1, in <module>
data = json.loads(temp)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting : delimiter: line 1 column 11 (char 10)

最佳答案

尝试 json.loads() 将 JSON 字符串加载(反序列化)到 Python dict 中:

>>> import json
>>> s = '{"max":28, "min":18, "custom":[{"id":"12345", "name":"test_pur"}]}'
>>> data = json.loads(s)
>>> print data["max"]
28

关于python - 在 python2.7 中将原始字符串转换为 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31533693/

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