简体   繁体   中英

Convert CSV to JSON using python pandas

Till now I can come up with this only:

filename = "newsample2.csv"
jsonFileName = "myjson2.json"

import pandas as pd
df = pd.read_csv ('newsample2.csv')

df.to_json ('myjson2.json', indent=4, orient='recod')

CSV File: https://drive.google.com/file/d/19u8M0wFrUq8E9um3l6sw0UZeQZRWTxNb/view?usp=sharing

Sample JSON (I need json in this format only) https://drive.google.com/file/d/1UXCi5u_ywmhst_vW3s1Z2HdjO_auFDZz/view?usp=sharing

Here is what you need to do.

  • Read the csv file using pandas.

csv_data = pd.read_csv('newsample.csv') final_dic_json = {"ReelStripsDefinition":[]}

  • Initialize lists to store temporary data. For example,

base_strip = []

  • Iterate over each column in DataFrame, and store data in lists created in last step.

  • Create a dictionary like this (I have used the keys as in json file you provided): base_strip1_dic = {"base_strip1": { "Enabled": true, "Stops": []}}

  • Similarly you will create other dictionaries.

  • Finally final_dic_json["ReelStripsDefinition"] = base_strip1_dic final_dic_json.append(base_strip2_dic) and so on.

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