简体   繁体   中英

How to parse nested Json using python and pandas?

I am trying to parse response I get from API. here is the format I have:

 jsn= " {'headers': ['deviceCategory', 'eventName', 'eventCount', 'eventValue'],
 'rows': [['desktop', 'page_v', '25213805', '0'],
  ['desktop', 'session_s', '32556', '0'],
  ['desktop', 'first_vis', '4324', '0'],
  ['desktop', 'user_eng', '2340', '0'],
  ['desktop', 'scroll', '3143', '0'],
  ['desktop', 'click', '3131', '0'],
  ['desktop', 'purchase', '2781', '581141.86'],
  ['desktop', 'file_download', '7475', '0'],
  ['desktop', 'view_search_results', '478', '0'],
  ['desktop', 'view_prom', '21', '0'],
  ['desktop', 'view_item', '1', '2.35']]}"

I have tried using:

import pandas as pd
df = pd.json_normalize(jsn)

I also tried using json_normalize from json library and I am not able to store this correctly into dataframe. As result i get column Header and Column row with just one line that contains all headers and all rows in each cell

在此处输入图像描述

How do i extract this data so i have 4 Columns as shown in headers and rows data populated below?

Assuming you have right json, the below should do:

import json
d = json.loads(jsn)
df = pd.DataFrame(columns = d['headers'], data = d['rows'])

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