我一直在试图找出一个在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格式的数据。

任何建议都将不胜感激。


当前回答

因为你的字符串是一个有效的JavaScript对象,你可以使用Js2Py库:

import js2py

content = """x = {'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}"""
content = js2py.eval_js(content)

print(content.to_dict())

其他回答

我也有类似的问题。两个相互通信的组件使用队列。

第一个组件没有执行json。在将消息放入队列之前转储。 因此接收组件生成的JSON字符串是单引号。这就导致了错误

 Expecting property name enclosed in double quotes

添加json。转储开始创建正确格式的JSON &解决问题。

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

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

在我的情况下,错误不是在json.loads(data)

我已经做了一些错误与json结构之前,所以有一个不足的部分在它,如

{'http://example.org/about': {'http://purl.org/dc/terms/title':

这也是引起这个错误的情况

因为JSON只允许用双引号括住字符串,你可以这样操作字符串:

s = s.replace("\'", "\"")

如果你的JSON包含转义单引号(\'),那么你应该使用更精确的以下代码:

import re
p = re.compile('(?<!\\\\)\'')
s = p.sub('\"', s)

这将把JSON字符串s中出现的所有单引号替换为双引号,在后一种情况下,不会替换转义的单引号。

你也可以使用不那么严格的js-beautify:

$ pip install jsbeautifier
$ js-beautify file.js

这很简单

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 "}'

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