-2

Want to update json file partially. Want to update different values different records.

Example:

[
 {
    "Id": "default",
    "AccountId":1,
 },
{
    "Id": "default",
    "AccountId":2,
}
]

Based on some inputs want to update only AccountId in the first record only.Is it possible to do that

MisterNox
  • 1,445
  • 2
  • 8
  • 22
  • Hello and welcome to stack overflow, please read [How do I ask a good question?](https://superuser.com/). For example you are not telling us what you have tried and your question completely lacks any code sample. – Ente Jul 29 '20 at 10:56

2 Answers2

1

You can modify json data by loading it with the method json.loads("Your_Json_String"). Then you can treat it like any other python dict/list.

import json

data = """[
    {"Id": "default", "AccountId":1},
    {"Id": "default", "AccountId":2}
    ]"""

json_dict = json.loads(data)

#update the first record
json_dict[0]["AccoundId"] = 10

print(json_dict)
#[{'Id': 'default', 'AccountId': 1, 'AccoundId': 10}, {'Id': 'default', 'AccountId': 2}]

#convert it to json again
json_data = json.dumps(json_dict)
MisterNox
  • 1,445
  • 2
  • 8
  • 22
0

You can treat this as a list. For example if you wanted to change the first one:

import json


jsonData = json.load(open("yourfile.json", "r"))

jsonData[0]["AccountId"] = 3

json.dump(jsonData, open("yourfile.json" ,"w"))
Marko Borković
  • 1,884
  • 1
  • 7
  • 22