Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

2 snippets
  • Writing JSON to a file in Python

    import json
    import os
    import uuid
    
    filename = str(uuid.uuid4()) # create random file name
    
    # JSON data to be written
    jsonDict ={
        "firstname" : "John",
        "lastname" : "Doe",
        "age" : 30,
        "phonenumber" : "9976770500"
    }
    
    # write JSON to file
    with open(filename, "w") as f:
        json.dump(jsonDict, f)
    
    # read JSON string from file
    f = open(filename, "r")
    print(f.read())
    f.close()
    os.remove(filename)
    
    # Output:
    # {"firstname": "John", "lastname": "Doe", "age": 30, "phonenumber": "9976770500"}

    You can write JSON to a file using the json.dump() function from the JSON module combined with file handling in Python. In thisexample, we open a file in writing mode. If the file doesn't exist, it will be created. The json.dump() function converts the Python dictionary into a JSON string, which is then saved in the file.

  • Read JSON file using Python

    import json
    import uuid
     
    jsonString = '{"firstname": "John", "lastname": "Doe"}'
    
    # Create random file name and write json to file
    filename = str(uuid.uuid4())
    
    with open(filename, "w") as f:
        f.write(jsonString)
    
    # Parse JSON string
    # Deserializes json string into dict
    print("Parse JSON string")
    jsonDict = json.loads(jsonString)
    
    # Iterating through the json
    for key, value in jsonDict.items():
        print(key, value)
    
    print()
    #----------------------------------------------------#
    
    print("Read JSON file")
    f = open (filename, "r")
     
    # Reading from file
    jsonDict = json.loads(f.read())
     
    # Iterating through the json
    for key, value in jsonDict.items():
        print(key, value)
     
    # Closing file
    f.close()
    
    # Output
    # Parse JSON string
    # firstname John
    # lastname Doe
    #
    # Read JSON file
    # firstname John
    # lastname Doe

    This exampleillustrates how to read from both a string and a JSON file. Initially, we have a JSON string stored in the variable 'jsonString'. We convert this JSON string into a Python dictionary using json.loads() method, which is then stored in the variable 'jsonDict'. Next, we read a JSON string stored in a file using json.loads(). To achieve this, we first convert the JSON file into a string using file handling, similar to the previous example. Then, we convert it into a string using the read() function. The subsequent steps mirror those followed earlier, utilizing the json.loads() method.