我一直在试图找出一个在Python中加载JSON对象的好方法。 我发送这个json数据:

{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}

到后端,它将作为一个字符串接收,然后我使用json.loads(数据)来解析它。

但每次我都得到相同的异常:

ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

我谷歌了一下,但似乎没有什么工作,除了这个解决方案json.loads(json.dumps(data)),这对我个人来说似乎不是那么有效,因为它接受任何类型的数据,甚至那些不是json格式的数据。

任何建议都将不胜感激。


当前回答

你可以使用json5包https://pypi.org/project/json5/而不是json包。这个包可以处理单引号。解码函数是json5.loads(data),类似于json包。

其他回答

下面的代码片段将有助于将数据转换为JSON。所有单引号都应该转换为双引号以jsonify数据。

data = {
"http://example.org/about": {
    "http://purl.org/dc/terms/title": [{
        "type": "literal",
        "value": "Anna's Homepage"
    }]
}}
parsed_data = data.replace("'", '"')
data_json = json.loads(parsed_data)

你可以使用json5包https://pypi.org/project/json5/而不是json包。这个包可以处理单引号。解码函数是json5.loads(data),类似于json包。

这很简单

import json

my_str = '{"message_type": "fixed_price_difference", "message": "Hello hello"}'

print(type(json.loads(my_str)), json.dumps(my_str))

Output:
    <class 'dict'> "{\"message_type\": \"fixed_price_difference\", \"message\": \"Hello hello\"}"

比如语法就很重要

语法错误,不正确: my_str = "{'message_type': 'fixed_price_difference', 'message': 'Hello Hello '}'

正确的语法: my_str = '{"message_type": "fixed_price_difference", "message": "Hello Hello "}'

最后: 声明字符串以引号开始和结束。

正如它清楚地说错了,名字应该用双引号括起来,而不是单引号。您传递的字符串不是有效的JSON。它应该是这样的

{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}

正如其他答案所解释的那样,错误发生是因为传递给json模块的无效引号字符。

在我的情况下,我继续得到ValueError,即使在替换'与'在我的字符串。我最终意识到,一些类似引号的unicode符号已经进入了我的字符串:

 “  ”  ‛  ’  ‘  `  ´  ″  ′ 

要清除所有这些,你可以通过一个正则表达式传递你的字符串:

import re

raw_string = '{“key”:“value”}'

parsed_string = re.sub(r"[“|”|‛|’|‘|`|´|″|′|']", '"', my_string)

json_object = json.loads(parsed_string)