jsonpython-3.xspacydoccano

Creating a JSON file in python, where they are not separated by commas


I'm looking to create the below JSON file in python. I do not understand how I can have multiple dictionaries that are not separated by commas so when I use the JSON library to save the dictionary to disk, I get the below JSON;

{"text": "Terrible customer service.", "labels": ["negative"], "meta": {"wikiPageID": 1}}

{"text": "Really great transaction.", "labels": ["positive"], "meta": {"wikiPageID": 2}}

{"text": "Great price.", "labels": ["positive"], "meta": {"wikiPageID": 3}}

instead of a list of dictionaries like below;

[{"text": "Terrible customer service.", "labels": ["negative"], "meta": {"wikiPageID": 1}},

{"text": "Really great transaction.", "labels": ["positive"], "meta": {"wikiPageID": 2}},

{"text": "Great price.", "labels": ["positive"], "meta": {"wikiPageID": 3}}]

The difference is, in the first example, each line is a dictionary and they are not in a list or separated by commas.

Whereas in the second example, which is what I'm able to come up with is a list of dictionaries, each dictionary separated by a comma.

I'm sorry if this a stupid question I have been breaking my head over this for weeks, and have not been able to come up with a solution.

Any help is appreciated.

And thank you in advance.


Solution

  • As @LaurinNiemeyer mentioned there is no way to store multiple separated Python dictionary objects in one json file without wrapping them in a list or a dictionary or other supported data structures by Python builtin library for json. However, there is a way to workaround this, it will export files as you wanted but keep in mind that this format is not json compliant even if the file have the '.json' extension!
    Let say you have the following dictionary objects that you want export:

    dict1 = {"text": "Terrible customer service.", "labels": ["negative"], "meta": {"wikiPageID": 1}}
    dict2 = {"text": "Really great transaction.", "labels": ["positive"], "meta": {"wikiPageID": 2}}
    dict3 = {"text": "Great price.", "labels": ["positive"], "meta": {"wikiPageID": 3}}
    

    To export the above dictionary objects you can simply do:

    objs_to_export = [dict1, dict2, dict3]
    with open("json_file.json", "a") as out_file:
    for obj in objs_to_export:    
        json.dump(obj, out_file)
        out_file.write('\n')