Home > Software engineering >  How can I put separate row of dictionary into Dataframe and export to csv file?
How can I put separate row of dictionary into Dataframe and export to csv file?

Time:02-10

Data is Dictionary in a separate line. How can I put it together into Dataframe and export to civ file?

json_responses = response.text.split('\n')
for item in json_responses:
    if item != '':
        dic = json.loads(item)
        print(dic)
{'sku_id': 'A', 'primary_category_code': 'AA52103320001', 'primary_store': 'F0001001'}
{'sku_id': 'B', 'primary_category_code': 'AA52103320001', 'primary_store': 'F0001001'}
{'sku_id': 'C', 'primary_category_code': 'AA52103320002', 'primary_store': 'F0001002'}
{'sku_id': 'D', 'primary_category_code': 'AA52103320002', 'primary_store': 'F0001002'}

CodePudding user response:

You can collect the dicts in a list and pass it to DataFrame constructor.

import json
lst_of_dic = [json.loads(item) for item in response.text.split('\n') if item != '']
df = pd.DataFrame(lst_of_dic)

Output:

  sku_id primary_category_code primary_store
0      A         AA52103320001      F0001001
1      B         AA52103320001      F0001001
2      C         AA52103320002      F0001002
3      D         AA52103320002      F0001002
  • Related