Home > OS >  Python: Change a JSON value
Python: Change a JSON value

Time:07-15

Let's say I have the following JSON file named output.

{'fields': [{'name': 2, 'type': 'Int32'},
  {'name': 12, 'type': 'string'},
  {'name': 9, 'type': 'datetimeoffset'},
 }],
 'type': 'struct'}

If type key has a value datetimeoffset, I would like to change it to dateTime and if If type key has a value Int32, I would like to change it to integer and like this, I have multiple values to replace.

The expected output is

{'fields': [{ 'name': 2, 'type': 'integer'},
  { 'name': 12, 'type': 'string'},
  { 'name': 9, 'type': 'dateTime'},
,
 }],
 'type': 'struct'}

Can anyone help with this in Python?

CodePudding user response:

You can try this out:

substitute = {"Int32": "integer", "datetimeoffset": "dateTime"}

x = {'fields': [
    {'name': 2, 'type': 'Int32'},
    {'name': 12, 'type': 'string'},
    {'name': 9, 'type': 'datetimeoffset'}
    ],'type': 'struct'}

for i in range(len(x['fields'])):
    if x['fields'][i]["type"] in substitute:
        x['fields'][i]['type'] = substitute[x['fields'][i]['type']]

print(x)

CodePudding user response:

You can use the following code. Include in equivalences dict the values you want to replace:

json = {
       'fields': [
           {'name': 2, 'type': 'Int32'},
           {'name': 12, 'type': 'string'},
           {'name': 9, 'type': 'datetimeoffset'},
                 ],
        'type': 'struct'
        }

equivalences = {"datetimeoffset": "dateTime", "Int32": "integer"}

#Replace values based on equivalences dict
for i, data in enumerate(json["fields"]):
    if data["type"] in equivalences.keys():
        json["fields"][i]["type"] = equivalences[data["type"]]

print(json)

The output is:

{
    "fields": [
        {
            "name": 2,
            "type": "integer"
        },
        {
            "name": 12,
            "type": "string"
        },
        {
            "name": 9,
            "type": "dateTime"
        }
    ],
    "type": "struct"
}

CodePudding user response:

simple but ugly way:

json_ ={'fields': [{'name': 2, 'type': 'Int32'},
                {'name': 12, 'type': 'string'},
                {'name': 9, 'type': 'datetimeoffset'}], 'type': 'struct'}
result = json.loads(json.dumps(json_ ).replace("datetimeoffset", "dateTime").replace("Int32", "integer"))
  • Related