skip to Main Content

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


  1. 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-in json module.

    import json
    
    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
            elif type(x) is str:
                try:
                    y = json.loads(x)
                    flatten(y, name)
                except:
                    out[name[:-1]] = x
            else:
                out[name[:-1]] = x
    
        flatten(json_data)
        return out
    
    json_data = {
      "id": "123",  
      "name": "Jack",  
      "createdAt": 20221212,  
      "region": '{"country": "USA", "city": "NewYork"}'
    }
    
    print(flatten_data(json_data))
    

    Output:

    {
      "id": "123",  
      "name": "Jack",  
      "createdAt": 20221212,  
      "region_country": "USA",
      "region_city": 'NewYork'
    }
    
    Login or Signup to reply.
  2. 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

     json_data = {
      "id": "123",  
      "name": "Jack",  
      "createdAt": 20221212,  
      "region": {"country": "USA", "city": "NewYork"}
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search