Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Json:Expecting property name enclosed in double quotes

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.

like image 886
raeX Avatar asked Oct 05 '22 21:10

raeX


People also ask

How do you fix expecting property name enclosed in double quotes?

The Python "JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" occurs when we try to parse an invalid JSON string (e.g. single-quoted keys or values, or a trailing comma). Use the ast. literal_eval() method to solve the error.

Does JSON have to be double quotes?

JSON names require double quotes.

Can you use a double quote inside a JSON string?

8. Can you use a double quote inside a JSON string? Yes, if you use the ascii code.

Are single and double quotes the same JSON?

As you can see from the code snippet, single quotes break JSON parsing. The technical reason has to do with the JSON specification (RFC 7159), which requires double quotes as the JSON string character.


2 Answers

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.

like image 281
ElmoVanKielmo Avatar answered Oct 08 '22 11:10

ElmoVanKielmo


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

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

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

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

This will replace all occurrences of single quote with double quote in the JSON string s 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
like image 128
elig Avatar answered Oct 08 '22 11:10

elig