skip to Main Content

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)

2

Answers


  1. I understand that you have a JSON file containing numbers as keys and URLs as values, and you want to extract and print only the URLs using Python. Based on the code you provided, it seems that you are on the right track, but you’re encountering an issue.

    To properly read the JSON file and print the URLs, you can modify your code as follows:

    import json
    
    with open('all_links_dict.json') as fd:
        json_data = json.load(fd)
        for key, value in json_data.items():
            print(value)
    

    This code snippet uses the json.load() function to load the JSON data from the file into a Python dictionary. Then, it iterates over the dictionary items and prints the values, which correspond to the URLs in your case.

    Make sure to replace 'all_links_dict.json' with the actual path to your JSON file. Running this updated code should print the URLs from your JSON file.

    Let me know if you have any further questions or issues.

    Login or Signup to reply.
  2. 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)}')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search