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

任何建议都将不胜感激。


当前回答

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

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

其他回答

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

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

因为你的字符串是一个有效的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("'", '"')

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

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

 “  ”  ‛  ’  ‘  `  ´  ″  ′ 

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

import re

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

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

json_object = json.loads(parsed_string)

对于任何想要快速修复的人来说,这只是将所有单引号替换为双引号:

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")