-2

I have uploaded a file here that I am trying to parse as JSON, but my code below is not working:

with open('all_links_dict.json') as fd:
    json_data = json.load(fd)
    print(json_data)
Booboo
  • 38,656
  • 3
  • 37
  • 60
Alberi
  • 13
  • 4

1 Answers1

0

If you have a trailing ',' in the file, then it must also be removed. The following code tests if for the comma and removes it (later I will show you something simpler and better):

Using json

import json

with open('all_links_dict.json') as fd:
    text = fd.read().strip()
    # Remove trailing ','
    if text[-1] == ',':
        text = text[:-1]
    json_data = json.loads('{' + text + '}')
    print(json_data)

Using ast.literal_eval

In this case we don't have to worry about a possible trailing ','.

import ast

with open('all_links_dict.json') as fd:
    text = fd.read()
    data = ast.literal_eval('{' + text + '}')
    print(data)

Update

If the above code is still not working, you can find the offending lines with:

import ast

with open('all_links_dict.json') as fd:
    for line in fd:
        try:
            data = ast.literal_eval('{' + line + '}')
        except Exception as e:
            print(f'Exception: {e}, line = {repr(line)}')
Booboo
  • 38,656
  • 3
  • 37
  • 60