我一直在试图找出一个在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字符串必须使用双引号。JSON python库强制这样做,所以你无法加载你的字符串。你的数据应该是这样的:

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

如果这不是你能做到的,你可以使用ast.literal_eval()而不是json.loads()

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

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美化工具,如json美化工具,因为它帮助我修复了json文件中尾随逗号的错误,该错误产生了相同的错误。

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

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

 Expecting property name enclosed in double quotes

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

x = x.replace("'", '"')
j = json.loads(x)

虽然这是正确的解决方案,但如果存在这样的JSON,可能会导致相当头痛-

{'status': 'success', 'data': {'equity': {'enabled': True, 'net': 66706.14510000008, 'available': {'adhoc_margin': 0, 'cash': 1277252.56, 'opening_balance': 1277252.56, 'live_balance': 66706.14510000008, 'collateral': 249823.93, 'intraday_payin': 15000}, 'utilised': {'debits': 1475370.3449, 'exposure': 607729.3129, 'm2m_realised': 0, 'm2m_unrealised': -9033, 'option_premium': 0, 'payout': 0, 'span': 858608.032, 'holding_sales': 0, 'turnover': 0, 'liquid_collateral': 0, 'stock_collateral': 249823.93}}, 'commodity': {'enabled': True, 'net': 0, 'available': {'adhoc_margin': 0, 'cash': 0, 'opening_balance': 0, 'live_balance': 0, 'collateral': 0, 'intraday_payin': 0}, 'utilised': {'debits': 0, 'exposure': 0, 'm2m_realised': 0, 'm2m_unrealised': 0, 'option_premium': 0, 'payout': 0, 'span': 0, 'holding_sales': 0, 'turnover': 0, 'liquid_collateral': 0, 'stock_collateral': 0}}}}

注意到“真实”的价值了吗?使用这个函数可以对布尔值进行双重检查。这将涵盖这些情况

x = x.replace("'", '"').replace("True", '"True"').replace("False", '"False"').replace("null", '"null"')
j = json.loads(x)

另外,确保你没有做出

x = json.loads(x)

它必须是另一个变量。