Parse CSV file to json with Python, parse json to csv

Asked 1 years ago, Updated 1 years ago, 59 views

Hello, I'm a total beginner in programming.

I'm going to use Python Parsing json to csv Parsing the csv (is that the term?) Is it encoding?I received a task to make it into a json file Our current level is that we know what JSON is I know the structure of the JSON file.

I know it's a ridiculous question, but I'd appreciate it if you could tell me what to look for first, even if it's not coding.

My current Python is 3.6.5 (I just installed the update)

If you show that you've studied a little,

For example, if I have a JSON file, After reading the json file, do you change it to csv?

If there is a structure of json file, how should you define it as a CSV file

Contrary to the above situation, if you have a csv file, I don't know how to change it to json file For example, I'd appreciate it if you could tell me

python csv json

2022-09-22 15:22

2 Answers

To be able to encode with CSV, the JSON file must be an array of objects with different values in the same key. For example:

[
  { { key1 : "foo",
    key2: "bar",
    ...
  },
  { { key2: "meh",
    ...
  },
  ...
]

So the plot that parses a string in JSON format and converts it to CSV format is roughly like this.


2022-09-22 15:22

It's weird that I'm answering and asking questions, If there's anyone who's watching, please let me know the weird part Thank you.

import csv import json

csvfile = open('test.csv','r') jsonfile = open(file='test_csv.json',mode='w')

fieldNames = ('A','B','C','D','E') reader = csv.DictReader(csvfile, fieldnames=fieldNames)

data = list(reader) json.dump(data,jsonfile,indent=4)

2.json -> csv

import csv import json

csvfile = open (file='test_json.csv',mode='w',newline='') jsonfile = open('test_csv.json','r')

fieldNames = ["A","B","C","D","E"] writer = csv.DictWriter(f=csvfile, fieldnames=fieldNames)

data = json.load(jsonfile) writer.writerows(data)


2022-09-22 15:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.