0

I get End of file expected.json in VS code and "JSON standard allows only one top-level value" in PyCharm , in the json file I am writing in even though the format is exactly the same as another json file that works perfectly fine. Please help me, I cant advance in my project because of this error:(, Here is the code where I write on the json file: `

# you can assume that abs_list is a list of pairs
with open('C:\\Users\\ruben\\Downloads\\NLP_Project-main\\cleanDataCategories.json', 'w') as json_file:
        for pair in abs_list:
            json_obj = {
                "abstract": pair[0],
                "category": pair[1]
            }
            json.dump(json_obj, json_file)
            json_file.write('\n')
`

I tried changing this but also didnt work this is really frustrating since I really dont know what could be wrong and feel like is not a problem of the structure or format that json file requires: `

# here I change the "" for '' and i surround the brackets with []
with open('C:\\Users\\ruben\\Downloads\\NLP_Project-main\\cleanDataCategories.json', 'w') as json_file:
        for pair in abs_list:
            json_obj = [{
                'abstract': pair[0],
                'category': pair[1]
            }]
            json.dump(json_obj, json_file)
            json_file.write('\n')`
  • 1
    The error means exactly what it says. You can only write one object to each JSON file. (Think about using a different format like JSONL instead). – Charles Duffy May 26 '23 at 13:31
  • but then how can I write in a json file such that in each line you have the pairs, there has to be a way since the json file that I use before to label the data has the exact same structure but the thing is is that in this case the file only lets me write one object meanwhile in the other json file it worked perfectly fine and doesnt give that error – Ruben de Lope May 26 '23 at 13:35
  • That means that file is written in [JSONL format](https://jsonlines.org/), not JSON. – InSync May 26 '23 at 13:38
  • 1
    [ECMA-404](https://www.ecma-international.org/wp-content/uploads/ECMA-404_2nd_edition_december_2017.pdf) only defines that a JSON *text* be one of the 7 defined JSON values (object, array, number, string, `true`, `false`, or `null`). It says nothing about reading a file assumed to contain one--or more--JSON texts. (The word "file" does not even appear in ECMA-404.) – chepner May 26 '23 at 13:44
  • 1
    The error you see would appear to stem from an attempt to *decode* a file using `json.load`, not writing the various objects to the file. (`json.loads` does expect only a single JSON text as its input, and `json.load(f)` is just a simple wrapper around `json.loads(f.read())`.) – chepner May 26 '23 at 13:47

0 Answers0