I have the following decoding function;
def flatten_data(json_data):
"""
Arguments:
json_data (dict): json data
Returns:
dict : {a:1, b:2, b_c:1, b_d:2}
"""
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '_')
elif type(x) is list:
out[name[:-1]] = x
else:
out[name[:-1]] = x
flatten(json_data)
return out
If I am giving the following JSON body input to this function;
{
"id": "123",
"name": "Jack",
"createdAt": 20221212,
"region": '{"country": "USA", "city": "NewYork"}'
}
I need to get the output as follows;
{
"id": "123",
"name": "Jack",
"createdAt": 20221212,
"region_country": "USA",
"region_city": 'NewYork'
}
How can I modify my flatten_data
function?
2
Answers
You can do it this way with some modification to your existing code where the value is
str
because in this case, the region has quotation""
. So to handle this you can use built-injson
module.Output:
Because your "region" key in json_data provides str data instead of dict that is why you are getting the wrong JSON value. please try to make it dict.
try this data