Python/Json:Expecting property name enclosed in double quotes

前端 未结 16 2207
南方客
南方客 2020-11-27 03:23

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/         


        
相关标签:
16条回答
  • 2020-11-27 03:35

    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.

    0 讨论(0)
  • 2020-11-27 03:35

    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
    
    0 讨论(0)
  • 2020-11-27 03:37

    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"}]}}
    
    0 讨论(0)
  • 2020-11-27 03:37

    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)
    
    
    0 讨论(0)
  • 2020-11-27 03:41
    with open('input.json','r') as f:
        s = f.read()
        s = s.replace('\'','\"')
        data = json.loads(s)
    

    This worked perfectly well for me. Thanks.

    0 讨论(0)
  • 2020-11-27 03:44

    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
    
    0 讨论(0)
提交回复
热议问题