Home > Enterprise >  json how to edit items user information with python
json how to edit items user information with python

Time:03-29

so if i had a json storing user info eg

 
{
    "joe": [
        {
            "name": "joe",
            "age": "28",
            "height": "",
            "Password": ""
        }
    ] }

how would change or append information so i can add info or change it using python so for example i get a input of 177 for the height how would i add it to data["joe"][0]["height"] using python

CodePudding user response:

Just assign the value to it

data = {"joe": [{"name": "joe", "age": "28", "height": "", "Password": ""}]}
data["joe"][0]["height"] = 177
print(data)
# {'joe': [{'name': 'joe', 'age': '28', 'height': 177, 'Password': ''}]}

Your format is strange, the idea of a name key is nice, but the array is strange idea, it doesn't seem to add anything

CodePudding user response:

You can use json.loads() to transform the JSON data to a dictionary, and then modify the dictionary as you normally would:

import json

json_data = """{
    "joe": [
        {
            "name": "joe",
            "age": "28",
            "height": "",
            "Password": ""
        }
    ] }"""

data_as_dictionary = json.loads(json_data)
data_as_dictionary['joe'][0]['height'] = input()
print(data_as_dictionary)

CodePudding user response:

You should remove the array from the json. Using name as a key is not really a good idea, what if there is 2 same names?

Json file:

{"joe": [{"name": "joe", "age": "28", "height": "", "Password": "" }]}

Python code:

from json import load, dump

with open('json_file', 'r') as f:
   users = load(f)
   # with load() you store json data into a dictionary, you can check by printing type()

users['joe'][0]['height'] = 177

with open('json_file', 'w') as f:
   dump(users, f)
   # with dump() you are storing new data into the json file

Edit: Btw you will probably see both load and loads, the s in load stands for "string" and it is used to load json data from a string, and load is used for loading json data from a file for example. The same goes for dump and dumps

  • Related