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

任何建议都将不胜感激。


当前回答

这很简单

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

在http://jsonlint.com/,结果是:

Error: Parse error on line 1:
{   'http://example.org/
--^
Expecting 'STRING', '}', got 'undefined'

将其修改为以下字符串解决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':

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

解决方案1(非常危险)

你可以简单地使用python的eval函数。

parsed_json = eval(your_json)

方案2(无风险)

你可以使用python默认包含的ast库,它也可以安全地计算表达式。

import ast

parsed_json = ast.literal_eval(your_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.dumps()方法总是理想的。 为了消除这个错误,我使用了以下代码

json.dumps(YOUR_DICT_STRING).replace("'", '"')