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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31533693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:11:02  来源:igfitidea点击:

Convert raw string to JSON object in python2.7

pythonjsonpython-2.7

提问by Aditya Patel

I am querying a PostgreSQL server to get data and a particular jsonobject actually gets returned as a string. I tried following but its not giving the correct output: (It's ipythonoutputs)

我正在查询 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\"}]}"'

How can i convert a string to json by recognizing the ":" symbol?

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

When i am trying "json.loads" . Following are the errors:

当我尝试 "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)

采纳答案by adrianus

Try json.loads()to load (deserialize) a JSON string into a Python dict:

尝试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

回答by Antoine

Your code is buggy. You should use json.loads()and not json.dumps()(if I understand your question right). Here you are converting a raw string to a JSON string. I thing you want to convert a JSON string to an JSON object no ?

你的代码有问题。你应该使用json.loads()而不是json.dumps()(如果我理解你的问题的话)。在这里,您将原始字符串转换为 JSON 字符串。我想将 JSON 字符串转换为 JSON 对象,不是吗?