简体   繁体   中英

How to replace value for a specific key in json file using python language

Json file

{
  "payloadFormatVersion": "9.0",
  "payload": {
    "ServiceConfiguration": {
      "LoggingSettings": {
        "NumberOfLogFilesToKeep": 7,
        "LogFileSizeBytes": 0,
        "LogFolderPath": "C:\\demo\\logs\\feature\\",
        "EnvironmentType": "testingenv",
        "DataRelayLogSink": {
          
          "PeriodInSeconds": 60,
          "TargetAddress": "http://localhost:portNumber/dumm1",
          "TargetTokenAddress": "http://localhost:portnumber/token",
          "PayloadType": "somedata",
          "TokenCredentials": {
            "ClientId": "testclientid",
            "ClientSecret": "testclientsecret",
            "GrantType": "testgranttype"
          }
        }
      },
      }
      }

JSON Content

def repalcejsonForSpecificKey(keyPath,fileName):
    filePath = "C:\\rajesh\\Configurations\\" + fileName + "\\" + fileName + ".json"
    print(filePath)
    Dict = {}
    with open(filePath) as f:
        superHeroSquad = json.load(f)
        duplicatedict={}
        duplicatedict=superHeroSquad
        testDict=getDictonaryItems(keyPath[0],**superHeroSquad)
        print(testDict)
def getDictonaryItems(searchKey, duplicatedict):
        if searchKey in duplicatedict.keys():
            testDict = duplicatedict[searchKey]
        return testDict

keyPath = ["payload","ServiceConfiguration", "TokenSettings", "ClientId"] fileName="vestas.sdh.dr.gateway" repalcejsonForSpecificKey(keyPath,fileName)

Below is my plan

  1. Method1 accepts 2 arguments JsonParsingKeyWhereToBereplaced, filename
  2. Redirecting Json file to dictonary
  3. call the method2 recursively where it accepts 2 arguments, one with searchKey and other is dictonary, this method will return all the key&values from specific Key passed on the method call Recursively call this method untill and unless you reach downstream key and update the value if found

kindly help me if any alternate way

Trying to update nested value from Json file using python language

Note: I could able to update the value in the Json file directly with below line superHeroSquad ['payload']['ServiceConfiguration']['TokenSettings']['ClientId'] = "text" But not like below superHeroSquad[keyPath[0][keyPath 1 ][keyPath[2]][keyPath[3]] = "text"

You could traverse your json as a map and replace the specific values like this:

import json


def replace_json_for_specific_key(file: str, key_pairs: dict[str, any]):
    content = json.load(open(file))

    for k, v in key_pairs.items():
        keys = k.split(".")
        element = content
        for key in keys[:-1]:
            element = element.setdefault(key, {})
        element[keys[-1]] = v

    tmp_file = open(file, "w")
    json.dump(content, tmp_file)
    tmp_file.flush()


if __name__ == '__main__':
    replace_json_for_specific_key(
        "input.json",
        {
            "payload.ServiceConfiguration.LoggingSettings.NumberOfLogFilesToKeep": 90,
            "payload.ServiceConfiguration.LoggingSettings.DataRelayLogSink.TokenCredentials.ClientId": "anothervalue"
        }
    )

Notice it will allow you to replace several values at once. You'll need to pass the dot (.) separated path to the specific key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM