Home > Net >  Reading and writing out a dictionary to csv file in python (or json)
Reading and writing out a dictionary to csv file in python (or json)

Time:11-30

I have a similar problem to this question here. But I got a json file that has to be converted to csv file through python. The json file is basically multiple python dictionary (example):

{
  "d" : {
    'a': 'one',
    'b': 'two',
    'c': 'three'
   },

 "z" : {
    'j': 'eleven',
    'k': 'twenty',
    'l': 'forty'
  }
}

I would like to write these dictionaries out to a csv file one after another (in a same column), in the format where each line contains the string key, followed by the string value.

I would also like to be able to read them all back into json file

I have tried to use the solution but I got an error saying that dict_items has no values

with open('some.json') as file:
data = json.load(file)
data_item = data["d"].items()

df = pd.DataFrame.from_dict(data_item, orient="index")
df.to_csv("data.csv")

For the expected output, click the link

any help would be appreciated.

CodePudding user response:

Here how to read a json file and save it to a csv:

import pandas as pd

with open('some.json', encoding='utf-8-sig') as f_input:
    df = pd.read_json(f_input)

df.to_csv('some.csv', encoding='utf-8', index=False)

CodePudding user response:

if you want to write one of the dictionaries, remove .items() and that's it.

  • Related