How to convert CSV file to a specific JSON format with nested objects?

2024/7/5 11:46:06

I want to populate my json message with data from a CSV file. I want each row to be a "new" json object. I am using Python and will connect the the code to an API once done. Some of the data needs tp be categorized under "personalinfo" and "carinfo" and I need the correct data to be populated under the right category as under the "Expected json message output" below.

This is what I have so far:

import csv
import jsoncsvfile = open('test.csv', 'r')
jsonfile = open('file.json', 'w')fieldnames = ("firstname","r", "lastname","r", "age","r", "gender","r","model","r", "price","r", "loan","r")
reader = csv.DictReader(csvfile, fieldnames)
out = json.dumps( [ row for >row in reader ] )
jsonfile.write(out)

I do not know how to add the two "personalinfo" and "carinfo" categories.

Example csv table:

 FirstName  LastName    Age gender  Car model Price loanAnna    Andersson   28  F       Audi    A8 40    FALSE

Expected json message output:

{"personalinfo": {"firstname": "Anna","lastname": "Andersson","age": "28","gender": "F","carinfo": [{"car": "Audi","model": "A8"}],"price": 40,"loan": "FALSE"}
}

Next record should be a new json object.

Answer

You need to convert each row of data in the csv file into a JSON object laid-out the way you described. This can be accomplished by calling a single function which takes the row dictionaries from the csv file using a csv.DictReader and does just that:

import csv
import jsondef make_record(row):return {"personalinfo": {"firstname": row["FirstName"],"lastname": row["LastName"],"age": row["Age"],"gender": row["gender"],"carinfo": [{"car": row["Car"],"model": row["model"]}],"price": int(row["Price"]),"loan": row["loan"]}}with open('csv_test.csv', 'r', newline='') as csvfile, \open('json_file.json', 'w') as jsonfile:reader = csv.DictReader(csvfile, delimiter='\t')out = json.dumps([make_record(row) for row in reader], indent=4)jsonfile.write(out)# Show results.
with open('json_file.json', 'r') as jsonfile:print('results:')print(json.dumps(json.load(jsonfile), indent=4))
https://en.xdnf.cn/q/120604.html

Related Q&A

How do I repeat the program? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to parse json data in Python? [duplicate]

This question already has answers here:How can I parse (read) and use JSON in Python?(5 answers)Closed 10 years ago.Please help me to parse this json in python.{ "IT" : [ { "firstName…

Why did they opt for the message most recent call last? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed last month.Improve …

AttributeError: NoneType object has no attribute current

class LoginScreen(Screen):def __init__(self,**kwargs):super(LoginScreen, self).__init__(**kwargs)print self,self.parent.currentclass AppScreenManager(ScreenManager):pass#Base Class class AppBaseClass(A…

Python urllib2 or requests post method [duplicate]

This question already has answers here:Submitting to a web form using python(3 answers)Closed 8 years ago.The community reviewed whether to reopen this question 9 months ago and left it closed:Original…

How to fix Django NoReverseMatch Error

I have built a simple blog app with Django and I have had some issue with NoReverseMatch. Here are my problem screenshots: https://prnt.sc/imqx70 https://prnt.sc/imqwptHere is my code on Github: https:…

Selenium NoSuchElementException with driver.find_element_by_xpath

First question: How do I make python minimize chrome? Second question: When getting to the end page using the next button how do I tell python to go on.. and not give me an error?driver.get("htt…

Traverse Non-Binary Tree [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

Muscle alignment in python

I have a problem with printing my output from muscle aligning in python. My code is:from Bio.Align.Applications import MuscleCommandline from StringIO import StringIO from Bio import AlignIOdef align_v…

why does my function is returning data type None??: Python datatype None

This is my python code for printing an absolute number. My function is returning type None. I am not getting what I have done wrong. Please help me. def n(num):if num<0:return (num*-1)no = input(&qu…