badah.blogg.se

Converting json to csv python
Converting json to csv python













converting json to csv python

Pandas has a convenient function for this: df.to_csv('input.csv', index=False, encoding='utf-8')Īnd here is the resulting CSV file: id,name,address.city

converting json to csv python converting json to csv python

Now that our data is normalized to a tabular format, let’s write our CSV file! In our case, if we print the resulting dataframe, it will look something like this: print(df) id name address.cityĪs you can see the address which was an object, was flattened out to a column. With open('input.json', encoding='utf-8') as file:īecause the JSON format can hold structured data like nested objects and arrays, we have to normalize this data so that it can be respresented in the CSV format.Ī quick way to do this is to use the pandas.normalize_json function, which will take JSON data and normalize it into a tabular format, you can read more about this function here. Let’s load the JSON file using the json Python module: import json You can install pandas using pip running this command: $ pip install pandas You could technically use the standard json and csv modules from Python to read the JSON file and write a CSV file, but depending on how your JSON file is structured, it can get complicated, and pandas has some great functions to handle these cases, without mentioning it’s really fast, so that’s what we will use. Let’s say we have a JSON file that looks like this: [ If you have any doubt, feel free to contact me at Twitter or by e-mail eu at this tutorial we’ll be converting a JSON file to CSV using Python. Python json_to_csv.py input.txt output.csv Hi everybody, this is a simple snippet to help you convert your JSON file to a CSV file using a Python script.Ĭreate a new Python file like: json_to_csv.pyĪdd this code: import csv, json, sys #if you are not using utf-8 files, remove the next line sys.setdefaultencoding("UTF-8") #set the encode to utf8 #check if you pass the input file and output file if sys.argv is not None and sys.argv is not None: fileInput = sys.argv fileOutput = sys.argv inputFile = open(fileInput) #open json file outputFile = open(fileOutput, 'w') #load csv file data = json.load(inputFile) #load json content inputFile.close() #close the input file output = csv.writer(outputFile) #create a csv.write output.writerow(data.keys()) # header row for row in data: output.writerow(row.values()) #values rowĪfter adding this, save the file and run at the terminal:

converting json to csv python

How to convert a JSON file to CSV - PYTHON SCRIPT















Converting json to csv python