Let’s say I have the following JSON file named output
.
JavaScript
x
6
1
{'fields': [{'name': 2, 'type': 'Int32'},
2
{'name': 12, 'type': 'string'},
3
{'name': 9, 'type': 'datetimeoffset'},
4
}],
5
'type': 'struct'}
6
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
JavaScript
1
7
1
{'fields': [{ 'name': 2, 'type': 'integer'},
2
{ 'name': 12, 'type': 'string'},
3
{ 'name': 9, 'type': 'dateTime'},
4
,
5
}],
6
'type': 'struct'}
7
Can anyone help with this in Python?
Advertisement
Answer
You can try this out:
JavaScript
1
14
14
1
substitute = {"Int32": "integer", "datetimeoffset": "dateTime"}
2
3
x = {'fields': [
4
{'name': 2, 'type': 'Int32'},
5
{'name': 12, 'type': 'string'},
6
{'name': 9, 'type': 'datetimeoffset'}
7
],'type': 'struct'}
8
9
for i in range(len(x['fields'])):
10
if x['fields'][i]["type"] in substitute:
11
x['fields'][i]['type'] = substitute[x['fields'][i]['type']]
12
13
print(x)
14