Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Can anyone help with this in Python?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading