Programmer120
Programmer120

Reputation: 2592

How to flat Json file using Python?

I have the following input: https://textuploader.com/dz3xo

This contains two orders.

The input can be converted into Json using:

print json.dumps(response2)

I want to manipulate this input to be shown as Json of like the following:

https://jsonblob.com/85f329dc-994c-11e8-8a91-931af4d591d9

The manipulation is simple: Any Sub-Json is removed and join to the father Json.

I wrote following functions:

def flatten_json(y):
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + str(a) + '_')
        elif type(x) is list:
            out[name[:-1]] = x
        else:
            out[name[:-1]] = x

    flatten(y)
    return out


def generatejson2(response2):
    sample_object = pd.DataFrame(response2).to_dict()
    flat = {k: flatten_json(v) for k, v in sample_object.items()}
    return json.dumps(flat, sort_keys=True)


response2 = Func_Create_Data()
flat_json = generatejson2(response2)

However this is not my desired out put it. It gives: enter image description here

It mix data from the two orders under the same index. The row numbers should never be in the index name.

I can't find the problem with my code. Any idea what's wrong?

Upvotes: 1

Views: 551

Answers (1)

Alexander Lupas
Alexander Lupas

Reputation: 61

Your flatten function should be working right, are you sure you're handing it the right information in the line

flat = {k: flatten_json(v) for k, v in sample_object.items()}

it looks a lot like the 'k' in that line is ['customer', 'shippingAddress', ...] rather than the expected ['0', '1']. My guess is you should have a

0_country_currency_id: 2

inside your shippingAddress?

Upvotes: 1

Related Questions