我一直在试图找出一个在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 

predictions = []

def get_top_k_predictions(predictions_path):
    '''load the predictions'''
    
    with open (predictions_path) as json_lines_file:
        for line in json_lines_file:
            predictions.append(json.loads(line.replace("'", "\"")))
            
    
get_top_k_predictions("/sh/sh-experiments/outputs/john/baseline_1000/test_predictions.jsonl")

其他回答

因为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

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

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

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

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

with open('input.json','r') as f:
    s = f.read()
    s = s.replace('\'','\"')
    data = json.loads(s)

这对我来说非常有效。谢谢。

使用json.dumps()方法总是理想的。 为了消除这个错误,我使用了以下代码

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

这很简单

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

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