ABusy_developerT
ABusy_developerT

Reputation: 544

Update a specific key in JSON Array using PYTHON

I have a JSON file which has some key-value pairs in Arrays. I need to update/replace the value for key id with a value stored in a variable called Var1

The problem is that when I run my python code, it adds the new key-value pair in outside the inner array instead of replacing:

PYTHON SCRIPT:

import json
import sys
var1=abcdefghi

with open('C:\\Projects\\scripts\\input.json', 'r+') as f:
    json_data = json.load(f)
    json_data['id'] = var1
    f.seek(0)
    f.write(json.dumps(json_data))
    f.truncate()

INPUT JSON:

{
    "channel": "AT",
    "username": "Maintenance",
    "attachments": [
      {
         "fallback":"[Urgent]:",
         "pretext":"[Urgent]:",
         "color":"#D04000",
         "fields":[
            {
               "title":"SERVERS:",
               "id":"popeye",
               "short":false
            }
         ]
      }
   ]
}

OUTPUT:

{
    "username": "Maintenance", 
    "attachments": [
        {
            "color": "#D04000", 
            "pretext": "[Urgent]:", 
            "fallback": "[Urgent]:", 
            "fields": [
                {
                    "short": false, 
                    "id": "popeye", 
                    "title": "SERVERS:"
                }
            ]
        }
    ], 
    "channel": "AT", 
    "id": "abcdefghi"
}

Upvotes: 1

Views: 6410

Answers (2)

Buzzkillionair
Buzzkillionair

Reputation: 379

To add to the earlier answer from akash, here is a way that you can make these changes in the event that you have multiple fields that contain ids that you want to change to this same variable. I know this likely wouldn't apply here (given that it is an id), but could be used as a broad example for when you want to set all values to the same value in a similar type of question. For example, if you wanted to set the id number for many fields to be unique, you could set var1 = 1 and then each time the for k in json_data loops, you increase the value of var1 by 1. This is not the example I have below, the example below would be to change all the Fields so they all have the same ID value.

Further adjustments can be made if you had multiple attachments as well (could not just use [attachments][0] as it'd only apply to the fields within the first attachment).

I just figured this knowledge could be good for someone to have at some point.

INPUT JSON

{
  "channel": "AT",
  "username": "Maintenance",
  "attachments": [
    {
      "fallback": "[Urgent]:",
      "pretext": "[Urgent]:",
      "color": "#D04000",
      "fields": [
        {
          "title": "SERVERS:",
          "id": "popeye",
          "short": false
        },
        {
          "title": "DUMMYDATA:",
          "id": "DORRIS",
          "short": false
        }
      ]
    }
  ]
}

CODE

var1 = 'abcdefghi'
json_file = "Some/file/path"
with open(json_file, 'r+') as f:
    json_data = json.load(f)
    for k in json_data['attachments'][0]['fields']:
        k['id'] = var1
    f.seek(0)
    f.write(json.dumps(json_data, indent=2))
    f.truncate()

OUTPUT

{
  "channel": "AT",
  "username": "Maintenance",
  "attachments": [
    {
      "fallback": "[Urgent]:",
      "pretext": "[Urgent]:",
      "color": "#D04000",
      "fields": [
        {
          "title": "SERVERS:",
          "id": "abcdefghi",
          "short": false
        },
        {
          "title": "DUMMYDATA:",
          "id": "abcdefghi",
          "short": false
        }
      ]
    }
  ]
}

I hope that this is useful to some extent.

Upvotes: 0

akash karothiya
akash karothiya

Reputation: 5950

Below will update the id inside fields :

json_data['attachments'][0]['fields'][0]['id'] = var1

Upvotes: 4

Related Questions