使用PYTHON更新JSON阵列中的特定键

时间:2017-11-17 11:53:59

标签: python arrays json

我有一个JSON文件,在Arrays中有一些键值对。我需要使用存储在名为 Var1

的变量中的值来更新/替换键 id 的值

问题在于,当我运行我的python代码时,它会在内部数组外部添加新的键值对,而不是替换:

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
            }
         ]
      }
   ]
}

输出

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

1 个答案:

答案 0 :(得分:2)

下面将更新字段内的id:

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