Python / Json:期望属性名称用双引号引起来

问题:Python / Json:期望属性名称用双引号引起来

我一直在尝试找到一种在Python中加载JSON对象的好方法。我发送此json数据:

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

到后端,它将在这里作为字符串接收,然后我用来json.loads(data)解析它。

但是每次我遇到同样的异常:

ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

我用谷歌搜索,但是除了这个解决方案之外json.loads(json.dumps(data))似乎什么都没用,在我个人看来,这种解决方案效率不高,因为它接受任何类型的数据,即使不是json格式的数据也是如此。

任何建议将不胜感激。

I’ve been trying to figure out a good way to load JSON objects in Python. I send this json data:

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

to the backend where it will be received as a string then I used json.loads(data) to parse it.

But each time I got the same exception :

ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

I googled it but nothing seems to work besides this solution json.loads(json.dumps(data)) which personally seems for me not that efficient since it accept any kind of data even the ones that are not in json format.

Any suggestions will be much appreciated.


回答 0

这个:

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

不是JSON。
这个:

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

是JSON。

编辑:
一些评论者建议以上是不够的。
JSON规范-RFC7159声明字符串以引号开头和结尾。那是"
单一仲裁'在JSON中没有语义,只能在字符串中使用。

This:

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

is not JSON.
This:

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

is JSON.

EDIT:
Some commenters suggested that the above is not enough.
JSON specification – RFC7159 states that a string begins and ends with quotation mark. That is ".
Single quoute ' has no semantic meaning in JSON and is allowed only inside a string.


回答 1

因为JSON仅允许使用双引号将字符串引起来,所以您可以像这样操作字符串:

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

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

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

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

您还可以使用js-beautify不太严格的方法:

$ pip install jsbeautifier
$ js-beautify file.js

as JSON only allows enclosing strings with double quotes you can manipulate the string like this:

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

if your JSON holds escaped single-quotes (\') then you should use the more precise following code:

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

This will replace all occurrences of single quote with double quote in the JSON string str and in the latter case will not replace escaped single-quotes.

You can also use js-beautify which is less strict:

$ pip install jsbeautifier
$ js-beautify file.js

回答 2

就我而言,双引号不是问题。

上一个逗号给了我同样的错误信息。

{'a':{'b':c,}}
           ^

为了删除该逗号,我编写了一些简单的代码。

import json

with open('a.json','r') as f:
    s = f.read()
    s = s.replace('\t','')
    s = s.replace('\n','')
    s = s.replace(',}','}')
    s = s.replace(',]',']')
    data = json.loads(s)

这对我有用。

In my case, double quotes was not a problem.

Last comma gave me same error message.

{'a':{'b':c,}}
           ^

To remove this comma, I wrote some simple code.

import json

with open('a.json','r') as f:
    s = f.read()
    s = s.replace('\t','')
    s = s.replace('\n','')
    s = s.replace(',}','}')
    s = s.replace(',]',']')
    data = json.loads(s)

And this worked for me.


回答 3

很简单,该字符串不是有效的JSON。如错误所述,JSON文档需要使用双引号。

您需要修复数据源。

Quite simply, that string is not valid JSON. As the error says, JSON documents need to use double quotes.

You need to fix the source of the data.


回答 4

我检查了您的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"
        }]
    }
}

I’ve checked your JSON data

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

in http://jsonlint.com/ and the results were:

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

modifying it to the following string solve the JSON error:

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

回答 5

JSON字符串必须使用双引号。JSON python库强制执行此操作,因此您无法加载字符串。您的数据需要如下所示:

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

如果那不是您可以做的,则可以使用ast.literal_eval()代替json.loads()

JSON strings must use double quotes. The JSON python library enforces this so you are unable to load your string. Your data needs to look like this:

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

If that’s not something you can do, you could use ast.literal_eval() instead of json.loads()


回答 6

import ast

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

json_data = ast.literal_eval(json.dumps(inpt))

print(json_data)

这样可以解决问题。

import ast

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

json_data = ast.literal_eval(json.dumps(inpt))

print(json_data)

this will solve the problem.


回答 7

正如错误地明确指出的那样,名称应该用双引号而不是单引号引起来。您传递的字符串不是有效的JSON。它看起来像

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

As it clearly says in error, names should be enclosed in double quotes instead of single quotes. The string you pass is just not a valid JSON. It should look like

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

回答 8

我使用这种方法并设法获得所需的输出。我的剧本

x = "{'inner-temperature': 31.73, 'outer-temperature': 28.38, 'keys-value': 0}"

x = x.replace("'", '"')
j = json.loads(x)
print(j['keys-value'])

输出

>>> 0

I used this method and managed to get the desired output. my script

x = "{'inner-temperature': 31.73, 'outer-temperature': 28.38, 'keys-value': 0}"

x = x.replace("'", '"')
j = json.loads(x)
print(j['keys-value'])

output

>>> 0

回答 9

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)

This worked perfectly well for me. Thanks.


回答 10

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

注意到“ True”值了吗?使用它可以对布尔值进行双重检查。这将涵盖这些情况-

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

另外,请确保您不

x = json.loads(x)

它必须是另一个变量。

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

Although this is the correct solution, but it may lead to quite a headache if there a JSON like this –

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

Noticed that “True” value? Use this to make things are double checked for Booleans. This will cover those cases –

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

Also, make sure you do not make

x = json.loads(x)

It has to be another variable.


回答 11

我有类似的问题。彼此通信的两个组件正在使用队列。

在将消息放入队列之前,第一个组件没有执行json.dumps。因此,接收组件生成的JSON字符串用单引号引起来。这导致错误

 Expecting property name enclosed in double quotes

添加json.dumps开始创建格式正确的JSON,并解决了问题。

I had similar problem . Two components communicating with each other was using a queue .

First component was not doing json.dumps before putting message to queue. So the JSON string generated by receiving component was in single quotes. This was causing error

 Expecting property name enclosed in double quotes

Adding json.dumps started creating correctly formatted JSON & solved issue.


回答 12

使用eval功能。

它解决了单引号和双引号之间的差异。

Use the eval function.

It takes care of the discrepancy between single and double quotes.


回答 13

其他答案很好地解释了错误,因为传递给json模块的引号字符无效。

就我而言,即使在字符串中替换'",我仍然继续出现ValueError 。我最终意识到,有些引号形式的unicode符号已进入我的字符串中:

           `  ´     

要清理所有这些,您只需通过正则表达式传递字符串即可:

import re

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

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

json_object = json.loads(parsed_string)

As the other answers explain well the error occurs because of invalid quote characters passed to the json module.

In my case I continued to get the ValueError even after replacing ' with " in my string. What I finally realized was that some quote-like unicode symbols had found their way into my string:

 “  ”  ‛  ’  ‘  `  ´  ″  ′ 

To clean all of these you can just pass your string through a regular expression:

import re

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

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

json_object = json.loads(parsed_string)


回答 14

手动编辑JSON时,我多次遇到此问题。如果有人要在不注意的情况下从文件中删除某些内容,则可能会引发相同的错误。

例如,如果缺少JSON最后的“}”,它将抛出相同的错误。

因此,如果您手动编辑文件,请确保按照JSON解码器的要求格式化文件,否则会遇到相同的问题。

希望这可以帮助!

I have run into this problem multiple times when the JSON has been edited by hand. If someone was to delete something from the file without noticing it can throw the same error.

For instance, If your JSON last “}” is missing it will throw the same error.

So If you edit you file by hand make sure you format it like it is expected by the JSON decoder, otherwise you will run into the same problem.

Hope this helps!


回答 15

使用该json.dumps()方法总是理想的。为了摆脱此错误,我使用了以下代码

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

It is always ideal to use the json.dumps() method. To get rid of this error, I used the following code

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