简体   繁体   English

使用 Python 将 JSON 数据转换为 CSV

[英]Convert JSON data into CSV using Python

I have a data in the below format in.json file.我在.json 文件中有以下格式的数据。 I need to read the.json file and convert it into csv.我需要阅读.json文件并将其转换为csv。 Below are the code which i am using to convert.下面是我用来转换的代码。 but it is not working.但它不工作。

import json
import csv
import pandas as pd
 
with open('my_output_file02.json') as json_file:
jsondata = json.load(json_file)
data_file = open('Name.csv', 'w', newline='')

for url in jsondata:
print(jsondata)
df = pd.DataFrame(data=json)
df.to_csv("output.csv", index=True)

JSON format: {"url": "https://example.com", "title": "Test test", "meta_desc": "test test"} {"url": "https://example.com/abc", "title": "Test test abc", "meta_desc": "test test abcd"} JSON 格式:{“url”:“https://example.com”,“title”:“Test test”,“meta_desc”:“test test”} {“url”:“https://example.com/ abc", "title": "测试测试 abc", "meta_desc": "测试测试 abcd"}

Try this:尝试这个:

import pandas
jsonFile = open("my_file.json", "r") 
jsonData = jsonFile.read() #just get your json as string

csvPandas = pandas.read_json(jsonData) #it will convert your json string in a pandas object (than can convert your data to csv)

csvFile = open("my_csv.csv", "w") #you open your outpur file (for writing your csv data)
csvFile.write(csvPandas.to_csv()) #you have your data converted with the method to_csv() of the pandas object instance

#you don't forget to close the files after its doned.
jsonFile.close()
csvFile.close()

Hope it helps: :)希望能帮助到你: :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM