473,683 Members | 2,643 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python: convert CSV string to JSON format

2 New Member
# Create a file with the name data_format.py
# Add the following functions to file data_format:
# function get_book_info() , the function askes the user to enter the following information:
# book title
# book ISBN
# book author last name
# book publisher
# year published
# book price in Canadian dollars.
# The function will eliminate leading and trailing spaces from title, ISBN, author name and publisher (use function strip ()).
# The function will return a string from the given information in the same order specified above, separated by forward slash (/)
# Note: price should be formatted to have two digits after the decimal point
# Function to_csv_format() , the function takes one parameter which is the string generated by get_book_info() , parse it and return a string of the provided information in a csv format.
# Function to_JSON_format( ), the function takes a CSV formatted string and returns the corresponding JSON format string. Use String Methods find() ,string slicing and string concatenation to implement the required functionality.
# Create a main function as shown in the in-class lab section. Add function calls to get the book information, produce and display the csv

def get_book_info() :
book_title = (input("Enter the book title: "))
book_ISBN = input("Enter book ISBN: ")
book_author_las t_name = input("Enter author last name: ")
book_publisher = input("Enter book publisher: ")
year_published = input("Enter year published: ")
book_price = float(input("Bo ok price: "))

book_title = book_title.stri p()
book_ISBN = book_ISBN.strip ()
book_author_las t_name = book_author_las t_name.strip()
book_publisher = book_publisher. strip()
year_published = year_published. strip()

return f"%s/%s/%s/%s/%s/%.2f"%(book_tit le,book_ISBN,bo ok_author_last_ name,book_publi sher,year_publi shed,book_price )

# Function to_csv_format() , the function takes one parameter which is the string generated by get_book_info() ,
# parse it and return a string of the provided information in a csv format.

def to_csv_format(s tring_data):

string_to_csv_f ormat = "".join(string_ data)
return string_to_csv_f ormat.replace("/",",")

#Function to_JSON_format( ), the function takes a CSV formatted string and
#returns the corresponding JSON format string. Use String Methods find() ,
#string slicing and string concatenation to implement the required functionality.

def to_JSON_format( csv_formatted_s tring_to_json):

string = csv_formatted_s tring_to_json.r eplace(",",":")
return string
Oct 12 '21 #1
3 11105
644 Recognized Expert Contributor
What's the question?
Oct 19 '21 #2
2 New Member
so I need to convert the CSV formatted string into JSON format and I am having a hard time finding the solution for that. Can you please help?
Oct 19 '21 #3
25 New Member
To convert a CSV string to JSON format in Python, you can use the built-in csv and json modules. Here is an example code that demonstrates how to do this:
import csv
import json
csv_string = """name,age,cit y
John,25,New York
Alice,30,Los Angeles
Bob,35,Chicago" ""

# Read the CSV string into a list of dictionaries
csv_data = []
reader = csv.DictReader( csv_string.spli tlines())
for row in reader:
csv_data.append (row)

# Convert the CSV data to JSON format
json_data = json.dumps(csv_ data)
print(json_data )

If you're looking to improve your coding skills or learn new technologies, Cetpa Infotech offers a range of courses and training programs to help you stay up to date with the latest developments in the field. Check out our website for more information.
Feb 20 '23 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Haoyu Zhang | last post by:
Dear Friends, Python assignment is a reference assignment. However, I really can't explain the difference in the following example. When the object is a list, the assignment seems to be a reference. However, when the object is a number, the story is so different. I don't understantd for what reason Python deals with them differently. The example is as follows: >>> a = >>> b = a
by: kathy | last post by:
I can not find something like atof() which can convert string to double. Can anyone help me?
by: Akihiro KAYAMA | last post by:
Hi all. I would like to ask how I can implement string-like class using tuple or list. Does anyone know about some example codes of pure python implementation of string-like class? Because I am trying to use Python for a text processing which is composed of a large character set. As the character set is wider than UTF-16(U+10FFFF), I can't use Python's native unicode string class.
by: Ursula | last post by:
Is it possible to convert a string in a file. The problem is this: I have an object string that is a file xml and I want to pass to Deserialize function, but Deserialize function expect an object of FileStream type and the mode access. There is a function Convert.ChangeType(object value, Type conversionType), but I cant write for example: Convert.ChangeType(mystring, FileStream); CAN YOU HELP ME????? thanks
by: ravibantu | last post by:
Hi guys, I am a newbie to python. Does anybody know how i can read a dat file into python and convert into xcel format? Thank you ravi
by: musclemilk | last post by:
Good day, now i know that someone was having the same error message and i read the thread but didnt help me out too much! so basically i have a command button that on a form that needs to open another form and give me the details of the current record that was selected on the previous form. here is the code i am using: Private Sub ouvrir_détails_location_Click() On Error GoTo Err_ouvrir_détails_location_Click
by: shiniskumar | last post by:
How to convert string to double? Ive got a double variable dTot; its value is 5.037717235E7 when i did FreemarkerTools.formatDecimal(dTot) i got it as string "50377172.35". now i want to pass it as a double value to the method format() which is shown below. when i do Double.parseDouble i get dTot as 5.037717235E7 CurrencyConverter.format(Double.parseDouble(FreemarkerTools.formatDecimal(dTot)));
by: foocc | last post by:
Hi, im trying to convert data reports (.dsr) in vb6 to crystal reports in vb.net. However, I cant seems to find it in my Microsoft Visual Studio 2005 Tools for Office. I've tried going to Project > Add New Item and Solution Explorer > Add > New Item ....but i cant find crystal reports in any of it....The only thing i found is report (.rdlc) Can report(.rdlc) be used to convert data reports in vb6 to vb.net? Or are there any other...
by: Brandon | last post by:
How do I convert a string to a char array? I am doing this so I can edit the string received from an sql query so I can remove unnecessary characters.
by: Chocolade | last post by:
Im using win32_printer and im adding to listbox1 a list of the printer properties. but then when im scrolling down in the listbox1 and getting to the last property i see the list of properties start over again from the begining. So its adding twice the list of properties of the printer to the listbox1 and i want to add it once. Now i found that when im adding first the list of printers connected to the pc to combobox1 i see like 3-4...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.