Skip to content
Advertisement

Python: Change a JSON value

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?

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement