Gliese Studio
Gliese Studio

Reputation: 81

how to edit a json file using python

First of all take a look at my json structure

{
    "some_id": [
        {
            "embed": False,
            "plain_msg": "Some text",
            "embed_text": [
                {
                    "title": "any title",
                    "body": "any bpdy text",
                    "color": "random color"
                }
            ]
        }
    ]
}

Lets say I have a json file as filename.json with the given json. Now I want to change value of embed without changing any other data.

I have a simple code

  with open('filename.json', 'r') as f:
      json_data = json.load(f)
  json_data['some_id'] = 'Some string'
    with open('filename.json', 'w') as f:
      json.dump(json_data, f, indent=2)

But this code can only write inside some_id and rewrite all value with the given string as

{
    "some_id": "Some string"
}

Please help me how can I do this! I need your help

Upvotes: 0

Views: 4864

Answers (3)

Cargo23
Cargo23

Reputation: 3189

json_data becomes a dictionary with the same structure as your JSON. To access 'inner' elements, you just have to navigate the dictionary structure.

See comment below.

  with open('filename.json', 'r') as f:
      json_data = json.load(f)
  json_data['some_id'][0]['embed'] = 'Some string' # On this line you needed to add ['embed'][0]
    with open('filename.json', 'w') as f:
      json.dump(json_data, f, indent=2)

Upvotes: 4

Gliese Studio
Gliese Studio

Reputation: 81

I got the solution after a lot testing and searching.

The correct code is

with open('filename.json', 'r') as f:
    json_data = json.load(f)

json_data['some_id'][0]['embed'] = 'Some string'
with open('filename.json', 'w') as f:
    json.dump(json_data, f, indent=2)

It neither duplicate any data nor delete any existing data just change. OMG I got it finally.

Upvotes: 4

André Lima
André Lima

Reputation: 11

If I understood it correctly, you want to edit the value on the file you already have ('filename.json'), and not create a new file with that one field edited.

In that case, you don't need the nested with open... structure. Also, notice you have to fully index the field you are trying to edit in the dictionary returned by the json.load() method. It will be under "some_id", but that key holds a list with one element, so then you need to refer to index0. Finally, the element on index0 is also a dictionary where the "embed" keys exist - and that's what you want to change.

Try this:

    with open('filename.json', 'r+') as f:
      json_data = json.load(f)
      json_data['some_id'][0]['embed'] = 'Some string'
      json.dump(json_data, f, indent=2)

Upvotes: 1

Related Questions