how to save into a json file in python - Expecting 'STRING', '}', got 'undefined'

90 Views Asked by At

I have been trying to write into a json file like this:

with open(file_out, 'w') as f:
            json.dump(dicts, f, indent=4)

dicts here is a list of dictionaries created in python, which looks like this:


[{'date': '2018-12-11',
  'base': 'EUR',
  'target': 'USD',
  'exchange_rate': 1.1379},
 {'date': '2018-12-11',
  'base': 'EUR',
  'target': 'JPY',
  'exchange_rate': 128.75},...]

when I check the output, I am getting this error on https://jsonlint.com/:

[{
        'date': '2018-12-11',
        'base_currency': 'EUR',
        'target_currency': 'USD',
        'exchange_rate': 1.1379
    },
    {
        'date': '2018-12-11',
        'base_currency': 'EUR',
        'target_currency': 'JPY',
        'exchange_rate': 128.75
    }
]

Error: Parse error on line 1:
[{      'date': '2018-12-11'
----^
Expecting 'STRING', '}', got 'undefined'

how can I put it into a valid json format? thank you v much.

the only thing I noticed it gives single instead of double quotes - yet I have used json.dump??

1

There are 1 best solutions below

2
On

Need to be double quotes to be a valid json. Did you actually open up and check the file? It should be in double quotes like below.

[{
        "date": "2018-12-11",
        "base_currency": "EUR",
        "target_currency": "USD",
        "exchange_rate": 1.1379
    },
    {
        "date": "2018-12-11",
        "base_currency": "EUR",
        "target_currency": "JPY",
        "exchange_rate": 128.75
    }
]

But you could also write it to file as a string:

import json

data = [{
        'date': '2018-12-11',
        'base_currency': 'EUR',
        'target_currency': 'USD',
        'exchange_rate': 1.1379
    },
    {
        'date': '2018-12-11',
        'base_currency': 'EUR',
        'target_currency': 'JPY',
        'exchange_rate': 128.75
    }
]

jsonStr = json.dumps(data).replace("'", '"')
with open('file_out.json', 'w') as f:
    json.dump(jsonStr, f)