How to edit json file in python

try this script:

with open["data.json"] as f:
    data = json.load[f]
    data["id"] = 134
    json.dump[data, open["data.json", "w"], indent = 4]

the result is:

{
    "name":"mynamme",
    "id":134
}

Just the arrangement is different, You can solve the problem by converting the "data" type to a list, then arranging it as you wish, then returning it and saving the file, like that:

index_add = 0
with open["data.json"] as f:
    data = json.load[f]
    data_li = [[k, v] for k, v in data.items[]]
    data_li.insert[index_add, ["id", 134]]
    data = {data_li[i][0]:data_li[i][1] for i in range[0, len[data_li]]}
    json.dump[data, open["data.json", "w"], indent = 4]

the result is:

{
    "id":134,
    "name":"myname"
}

you can add if condition in order not to repeat the key, just change it, like that:

index_add = 0
n_k = "id"
n_v = 134
with open["data.json"] as f:
    data = json.load[f]
    if n_k in data:
        data[n_k] = n_v
    else:
       data_li = [[k, v] for k, v in data.items[]]
       data_li.insert[index_add, [n_k, n_v]]
       data = {data_li[i][0]:data_li[i][1] for i in range[0, len[data_li]]}
    json.dump[data, open["data.json", "w"], indent = 4]

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The full form of JSON is JavaScript Object Notation. It means that a script [executable] file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. 
     

    Functions Used: 
     

    • json.loads[]: json.loads[] function is present in python built-in ‘json’ module. This function is used to parse the JSON string.
       

    Syntax: json.loads[json_string]
    Parameter: It takes JSON string as the parameter.
    Return type: It returns the python dictionary object. 
     

    • json.dumps[]: json.dumps[] function is present in python built-in ‘json’ module. This function is used to convert Python object into JSON string.
       

    Syntax: json.dumps[object]
    Parameter: It takes Python Object as the parameter.
    Return type: It returns the JSON string. 
     

    • update[]: This method updates the dictionary with elements from another dictionary object or from an iterable key/value pair.
       

    Syntax: dict.update[[other]]
    Parameters: Takes another dictionary or an iterable key/value pair.
    Return type: Returns None. 
     

    Example 1: Updating a JSON string.
      

    Python3

    import json

    x =  '{ "organization":"GeeksForGeeks",

            "city":"Noida",

            "country":"India"}'

    y = {"pin":110096}

    z = json.loads[x]

    z.update[y]

    print[json.dumps[z]]

    Output:
     

    {“pin”: 110096, “organization”: “GeeksForGeeks”, “country”: “India”, “city”: “Noida”} 
     

    Example 2: Updating a JSON file. Suppose the JSON file looks like this.
     

    We want to add another JSON data after emp_details. Below is the implementation.

    Python3

    import json

    def write_json[new_data, filename='data.json']:

        with open[filename,'r+'] as file:

            file_data = json.load[file]

            file_data["emp_details"].append[new_data]

            file.seek[0]

            json.dump[file_data, file, indent = 4]

    y = {"emp_name":"Nikhil",

         "email": "",

         "job_profile": "Full Time"

        }

    write_json[y]

    Output:
     


    How do I edit a JSON file?

    Procedure.
    In the Enterprise Explorer view, right-click your . ... .
    You can compress JSON strings so that the strings display on one line with white space removed between JSON elements. ... .
    To format the content so that it is more readable, right-click the editor and select Source > Format from the menu or press Ctrl + Shift + F..

    How do I change the value of a JSON file?

    First you would need to convert it to a JavaScript Object. Once it is an Object, then you can just use dot notation into the object to change the values that you want. Lastly, you would convert that JavaScript Object back into a JSON string.

    How do I change the value of a JSON object in Python?

    Updating a JSON object in Python is as simple as using the built-in update[] function from the json package we have imported. The update method is used to add a new key-value pair to the JSON string that we declared in our code.

    How do I add data to an existing JSON object in Python?

    In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict [or list ] object by modifying it. Write the updated dict [or list ] object into the original file.

    Chủ Đề