Python/Json:Expecting property name enclosed in double quotes

前端 未结 16 2205
南方客
南方客 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:26

    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.

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

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

    Use the eval function.

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

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

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

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

    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.

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

    0 讨论(0)
提交回复
热议问题