简体   繁体   中英

Extracting JSON like data from pandas data frame to separate columns

Here is sample data:

{"Navbar":{"appId":"metaManagement","masked":true},"control":{"control":"accountNumber","id":"6789","value":null,"masked":false}}

{"Navbar":{"appId":"metaManagement","masked":true},"control":{"control":"accountNumber","id":"12345","value":null,"masked":false}}

I have searched many blogs & platforms but having no proper solution available. Can I fetch appID into separate column? Please help.

You can try this,

>>> from pandas.io.json import json_normalize
>>> d = {"Navbar":{"appId":"metaManagement","masked":"true"},"control":{"control":"accountNumber","id":"6789","value":"null","masked":"false"}}
>>> json_normalize(d)
     Navbar.appId Navbar.masked control.control control.id control.value control.masked
0  metaManagement          true   accountNumber       6789          null          false

Another way to do it if data is in pandas dataframe column.

    import json

    for i in range(len(df)):
        try:
           data = json.loads(df['jsonColumn'][i])

           df['jsonColumn1_Revised'][i] = data['Navbar']['appId']
           df['jsonColumn2_Revised'][i] = data['Navbar']['masked']
        except:
           continue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM