Python read csv to json

Преобразование файла CSV в JSON в Python – простой пример

В этом руководстве мы рассмотрим, как преобразовать файл в формате CSV в файл в формате JSON с помощью языка программирования Python. Но сначала давайте разберемся, что означают файлы CSV и JSON.

Что это за файл CSV?

Файл CSV – это сокращение от Comma Separated Values file, представляет собой простой текстовый файл, в котором хранится список данных. Файлы CSV обычно используются для обмена данными между различными приложениями. Менеджеры контактов и базы данных обычно поддерживают файлы CSV.

Файлы CSV также известны как файлы с разделителями-запятыми или значениями, разделенные символами. В этих файлах в основном используется символ запятой для разделения данных. Однако иногда можно использовать другие символы, например точку с запятой. Предполагается экспортировать сложные данные из одной программы в файл в формате CSV, а затем импортировать данные из файла CSV в другую программу.

Читайте также:  Css div 2 ids

Файл со значениями, разделенными запятыми (CSV) имеет довольно простую структуру, содержащую некоторые данные, перечисленные и разделенные запятыми. Файлы CSV разработаны таким образом, что они могут легко импортировать и экспортировать данные из других приложений. Полученные данные легко читаются людьми и могут просматриваться с помощью текстового редактора, такого как Блокнот, или приложения для работы с электронными таблицами, такого как Microsoft Excel или Google Таблицы.

Что такое файл JSON?

Файл JSON, также сокращенно от JavaScript Object Notation file, – это файл, который позволяет пользователям хранить основные объекты и структуру данных в стандартном формате обмена данными, называемом форматом JSON. Файл JSON обычно используется для передачи данных между веб-приложением и сервером. Файлы JSON – это легкие текстовые файлы, которые можно легко прочитать, и мы можем редактировать эти файлы с помощью текстового редактора, такого как Блокнот.

Формат JSON действительно основан на подмножестве JavaScript. Однако он называется независимым от языка форматом и поддерживается множеством программных API. JSON обычно используется в программировании веб-приложений Ajax. За последние несколько лет популярность JSON в качестве альтернативы XML постепенно растет.

Хотя существуют различные программы, которые используют JSON для обмена данными, они не могут сохранять файлы формата JSON на своем жестком диске. Обмен данными происходит между компьютерами, подключенными через Интернет. Тем не менее, несколько программ позволяют нам сохранять файлы в формате JSON. Например, Google+ использует файл JSON для сохранения данных профиля.

После входа в систему мы можем выбрать страницу «Освобождение данных» и выбрать опцию «Загрузить данные вашего профиля».

Поскольку файлы JSON представляют собой простые текстовые файлы, что позволяет нам открывать их в любом текстовом редакторе, таком как Microsoft Notepad для Windows, Apple TextEdit для Mac, Vim для Linux и GitHub Atom, мы также можем использовать веб-браузеры, такие как Google Chrome и Mozilla Firefox, чтобы открывать файлы формата JSON.

Теперь давайте начнем с преобразования файла CSV в файл JSON.

Преобразование файла CSV в файл JSON

Мы преобразуем CSV-файл в JSON-файл с помощью простой программы Python, как показано ниже.

Мы будем использовать следующий файл CSV.

Файл: mydatalist.csv

# importing the required libraries import csv import json # defining the function to convert CSV file to JSON file def convjson(csvFilename, jsonFilename): # creating a dictionary mydata = <> # reading the data from CSV file with open(csvFilename, encoding = 'utf-8') as csvfile: csvRead = csv.DictReader(csvfile) # Converting rows into dictionary and adding it to data for rows in csvRead: mykey = rows['S. No.'] mydata[mykey] = rows # dumping the data with open(jsonFilename, 'w', encoding = 'utf-8') as jsonfile: jsonfile.write(json.dumps(mydata, indent = 4)) # filenames csvFilename = r'mydatalist.csv' jsonFilename = r'mydatalist.json' # Calling the convjson function convjson(csvFilename, jsonFilename)
< "1": < "S. No.": "1", "Name": "Dave", "Age": "17" >, "2": < "S. No.": "2", "Name": "Albus", "Age": "16" >, "3": < "S. No.": "3", "Name": "John", "Age": "19" >, "4": < "S. No.": "4", "Name": "Tom", "Age": "22" >, "5": < "S. No.": "5", "Name": "Harry", "Age": "19" >, "6": < "S. No.": "6", "Name": "Ron", "Age": "20" >, "7": < "S. No.": "7", "Name": "William", "Age": "13" >, "8": < "S. No.": "8", "Name": "George", "Age": "15" >, "9": < "S. No.": "9", "Name": "Mark", "Age": "11" >, "10": < "S. No.": "10", "Name": "Max", "Age": "18" >>

В приведенном выше примере мы импортировали библиотеки csv и json и определили функцию как convjson(). Затем мы создали пустой словарь и прочитали данные из файла CSV. Мы преобразовали строки из CSV в словарь и добавили их к данным. Затем мы выгрузили данные в файл JSON. Наконец, мы определили переменные для имен путей к файлам и вызвали функцию convjson() для реализации преобразования.

В результате, когда мы выполнили программу, файл CSV был успешно преобразован в файл JSON.

Источник

Convert CSV to JSON Using Python – A Beginner’s Guide

Converting CSV File To JSON File Using Python 1 Png

In this article, we will convert CSV to JSON using a simple Python script. We’ll learn how to use the JSON (JavaScript Object Notation) library of Python and will try to understand the logic behind this conversion.

Why would you want to convert CSV to JSON?

JSON is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications, so whenever there’s a need to send some data from the server to the client, the data is first converted to JSON and then sent to the client so it can be displayed on a web page, or vice versa.

Steps Involved in Converting CSV to JSON

We will approach his problem in various small steps so that we understand the problem thoroughly and easily.

Step 1: Take input the CSV file and the JSON file paths

This can be achieved with the help of the input function. Input function by default takes input in the form of a string and this is exactly what we need. Input function can also be used to display some string while asking for input

Step 2: Open the CSV file using a file handler

A file handler can easily be initiated, there are many ways to do this but we will stick to the safest one i.e. we will use:

with open(csv_file_path, encoding = 'utf-8') as csv_file_handler:

This will open the file in reading mode, and as soon as we move out of this block, it’ll automatically close this file. Closing a file after use is very important to prevent the file from corrupting or any chances of data loss.

Step 3: Open the JSON file using JSON file handler

This file will be opened in write mode and thus the code changes to:

with open(json_file_path, 'w', encoding = 'utf-8') as json_file_handler:

Here ‘+w’ represents that the file is being opened in write mode, i.e. its data can be changed

Step 4: Parse the file into a JSON file using the functions of the JSON module

This task can easily be accomplished by using the following piece of code:

json_file_handler.write(json.dumps(data_dict, indent = 4))

And you’re all set, now you just need to run the code and your job will be done

Complete Code to Convert CSV to JSON in Python

import csv import json def csv_to_json(csv_file_path, json_file_path): #create a dictionary data_dict = <> #Step 2 #open a csv file handler with open(csv_file_path, encoding = 'utf-8') as csv_file_handler: csv_reader = csv.DictReader(csv_file_handler) #convert each row into a dictionary #and add the converted data to the data_variable for rows in csv_reader: #assuming a column named 'No' #to be the primary key key = rows['Serial Number'] data_dictPython read csv to json = rows #open a json file handler and use json.dumps #method to dump the data #Step 3 with open(json_file_path, 'w', encoding = 'utf-8') as json_file_handler: #Step 4 json_file_handler.write(json.dumps(data_dict, indent = 4)) #driver code #be careful while providing the path of the csv file #provide the file path relative to your machine #Step 1 csv_file_path = input('Enter the absolute path of the CSV file: ') json_file_path = input('Enter the absolute path of the JSON file: ') csv_to_json(csv_file_path, json_file_path)

Running The Code

Input Csv File

Command For Running The Script

$ python3 "python script name without quotes"

Running Python Script In Terminal

Output File

Json File Generated As Output

Conclusion

In this article, we learned how to implement a Python script that can create/convert CSV to JSON. We also learned about the ‘json‘ and ‘csv‘ modules of Python and their common functions.

Источник

Python – Convert CSV to JSON

To convert CSV to JSON in Python, follow these steps.

  1. Initialize a Python List.
  2. Read the lines of CSV file using csv.DictReader() function.
  3. Convert each line into a dictionary. Add the dictionary to the Python List created in step 1.
  4. Convert the Python List to JSON String using json.dumps().
  5. You may write the JSON String to a JSON file.

The format of CSV input and JSON output would be as shown in the following.

Input – data.csv

column_1,column_2,column_3 value_1_1,value_1_2,value_1_3 value_2_1,value_2_2,value_2_3 value_3_1,value_3_2,value_3_3

Output – data.json

Examples

1. Convert CSV file to JSON

In this example, we will read the following CSV file and convert it into JSON file.

data.csv – CSV File

a,b,c 25,84,com 41,52,org 58,79,io 93,21,co

Python Program

import csv import json def csv_to_json(csvFilePath, jsonFilePath): jsonArray = [] #read csv file with open(csvFilePath, encoding='utf-8') as csvf: #load csv file data using csv library's dictionary reader csvReader = csv.DictReader(csvf) #convert each csv row into python dict for row in csvReader: #add this python dict to json array jsonArray.append(row) #convert python jsonArray to JSON String and write to file with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonString = json.dumps(jsonArray, indent=4) jsonf.write(jsonString) csvFilePath = r'data.csv' jsonFilePath = r'data.json' csv_to_json(csvFilePath, jsonFilePath) 

data.json Output File

Summary

In this Python JSON Tutorial, we learned how to convert a CSV file to JSON file using csv and json libraries.

Источник

How to Convert CSV to JSON String using Python

Data to Fish

You may use the following template in order to convert CSV to a JSON string using Python:

import pandas as pd df = pd.read_csv (r'Path where the CSV file is saved\File Name.csv') df.to_json (r'Path where the new JSON file will be stored\New File Name.json')

Next, you’ll see the steps to apply the above template in practice.

Steps to Convert CSV to JSON String using Python

Step 1: Prepare the CSV File

Prepare the CSV file that you’d like to convert to a JSON string.

For example, let’s prepare a CSV file (called ‘Products‘) that contains the following information:

Product Price
Desktop Computer 700
Tablet 250
Printer 120
Laptop 1200

Step 2: Install the Pandas Package

If you haven’t already done so, install the Pandas package. You may use the following syntax to install the Pandas package under Windows:

Step 3: Convert the CSV to JSON String using Python

You may now use the following template to assist you in the conversion of the CSV file to a JSON string:

import pandas as pd df = pd.read_csv (r'Path where the CSV file is saved\File Name.csv') df.to_json (r'Path where the new JSON file will be stored\New File Name.json')
  • The path where the CSV file is saved is: C:\Users\Ron\Desktop\Test\Products.csv
    • Where ‘Products‘ is the file name, and ‘csv‘ is the file extension
    • Where ‘New_Products‘ is the new file name, and ‘json‘ is the file extension

    You’ll need to modify the paths to the location where the files will be stored on your computer.

    Here is the complete Python code to convert the CSV file to the JSON string for our example:

    import pandas as pd df = pd.read_csv (r'C:\Users\Ron\Desktop\Test\Products.csv') df.to_json (r'C:\Users\Ron\Desktop\Test\New_Products.json')

    Run the code in Python (adjusted to your paths), and the new JSON file will be created at your specified location.

    If you open the JSON file, you’ll see the following string:

    You may also want to check the following guides that explain how to convert:

    Источник

Оцените статью