skip to Main Content

Let’s say I have a dictionary in a .json file, created from a Python dictionary and dumped into this file with json.dump(my_dict, open("file.json", "r"), indent=4):

{
    "Amazon": {
        "email": "[email protected]",
        "password": "123456",
    }
}
{
    "Stack Overflow": {
        "email": "[email protected]",
        "password": "password",
    }
}

How would I access one of the two dictionaries later in my Python code? There are multiple dictionaries so I can’t simply read the .json file to get one and only one dictionary.

I’ve tried something like assigning the json.dump() part to a variable but it still couldn’t access a specific dictionary. Basically, the main issue is that I don’t have variable-assigned dictionaries or something else to find one particular .json dictionary. Any help would be appreciated. Thanks!

2

Answers


  1. If you update your file to contain a single JSON object, you can access the dictionaries within it using the json.load() function.

    with open("file.json") as json_file:
    items = json.load(json_file)
    
    dict1 = items[0]
    
    Login or Signup to reply.
  2. You do not have a JSON file. You have a file that is a concatenation of multiple JSON documents. json.load cannot handle this; you have to go lower level with JSONDecoder.raw_decode. This code will load your file into a list:

    import json
    
    with open('file.json', 'rt') as r:
        raw_json = r.read()
    
    decoder = json.JSONDecoder()
    items = []
    while raw_json:
        item, pos = decoder.raw_decode(raw_json)
        raw_json = raw_json[pos:].strip()
        items.append(item)
    
    from pprint import pprint
    pprint(items)
    
    # => [{'Amazon': {'email': '[email protected]', 'password': '123456'}},
    #     {'Stack Overflow': {'email': '[email protected]',
    #                         'password': 'password'}}]
    

    (assuming the file doesn’t actually have trailing commas before closing braces)

    Of course, if you only wish to read the n-th record, you can stop reading after having read n records, instead of accumulating the results in a list.

    Note that this is not a standard format. Not all programming languages allow you to JSON-parse a prefix of a string (e.g. in JavaScript you would either have to write a custom parser from scratch, or hack the error message to see where the error occured so you can cut the string off there — neither option is pretty). Use standard formats wherever possible. For example, JSONL (the same format but unindented, with one JSON document per line) is easily parseable in any language because you can predictably cut the raw string into lines before JSON parsing commences, while still being appendable, like your format.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search