Как конвертировать json в csv python

How to convert JSON to CSV in Python?

JSON (JavaScript Object Notation) is a popular data storing and transferring tool used in many server-side programming. Python supports JSON using its in-built package called json. We can convert a JSON structure into a comma-delimited textual structure. In this article, you will learn about the different methods to convert JSON to CSV structure.

What are CSV files?

CSV (Comma Separated Values) is a file format utilized for storing data in a tabular fashion. The structure of a CSV file can be interpreted in a spreadsheet or database format. It can store data in plain text (usually, string & number data type). Each line of a .csv file defines a data record. The record will contain one or more fields that are comma-separated values.

Converting JSON to CSV

JSON data usually contains data in key-value pairs. These keys will be the headers for the CSV file and the values as descriptive data that remain indented in json.

Method 1: Using CSV module:

It is a built-in Python module that implements classes for reading & writing tabular data in CSV structure. Using this, programmers can write this data in the format approved by Excel or read data from excel or CSV files. Programmers and developers can also represent the CSV formats recognized by other apps or define their special-purpose CSV formats. It is the most widely used module. Since it is a built-in module, you do not need to install it separately.

Program:

Explanation:

First, we will import the json and csv modules. Next, we will open the JSON file & load its data in the ‘data’ object. Next, we have to open a CSV file for writing in write mode. We assigned the count variable to zero. Then, use the for loop to fetch the data from the stud_data. Now, assign the cnt.keys() in the header. Provide the csv_writer.writerow() method and pass the header as the argument. Once you count the values, you should close the data_file.close() .

Method 2: Using Pandas Library:

It is a fast, flexible, powerful, & easy to implement open-source data analysis tool developed on top of Python language. It is a data manipulation & analysis library that worked well with conversations and various files like CSV, JSON, etc. Here, we will use the to_scv() method to convert a file to CSV.

Program:

Explanation:

First, we will import the pandas library, path, and json modules. Fetch the json file path using the Path() constructor and assign it to the jsonpath object. Next, you have to read the json file and assign it to the ‘dat’ object. Then, create the Dataframe using json_normalize() method and pass the ‘dat’ object into it as the parameter. Finally, convert the df.to_csv() method to convert the dataframe object to csv format with the filename ‘datafile.csv‘, having encoding scheme as UTF-8, and index as False.

Conclusion:

Both these methods are used to convert a JSON structure to a CSV file. But using the CSV module is beneficial because it is a built-in module and hence lighter as compare to the Pandas library. Also, the dataframe conversion takes more time making it complex. Hence, the first method should be preferred.

How to Convert a JSON String to CSV using Python

In this guide, you’ll see the steps to convert a JSON string to CSV using Python.

To begin, you may use the following template to perform the conversion:

In the next section, you’ll see how to apply the above template in practice.

Steps to Convert a JSON String to CSV using Python

Step 1: Prepare a JSON String

To start, prepare a JSON string that you’d like to convert to CSV.

For example, let’s say that you’d like to prepare a JSON string based on the following information about different products:

Product Price
Desktop Computer 700
Tablet 250
Printer 100
Laptop 1200

This is how the JSON string would look like for our example:

Step 2: Create the JSON File

Once you have your JSON string ready, save it within a JSON file.

Alternatively, you may copy the JSON string into Notepad, and then save that file with a .json extension.

For our example, save the notepad as Product_List.json. Don’t forget to add the .json extension at the end of the file name.

Step 3: Install the Pandas Package

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

Step 4: Convert the JSON String to CSV using Python

You may now use the following template to assist you in converting the JSON string to CSV using Python:

For our example:

  • The path where the JSON file is saved is: C:\Users\Ron\Desktop\Test\Product_List.json
    • Where ‘Product_List‘ is the file name, and ‘json‘ is the file extension
    • Where ‘New_Products‘ is the new file name, and ‘csv‘ is the file extension

    Note that you’ll need to adjust the paths to reflect the location where the files will be stored on your computer.

    Here is the complete Python code to perform the conversion to CSV for our example:

    Run the code (adjusted to your paths) and you’ll see the new CSV file at your specified location.

    Once you open the file, you’ll get the data about the products:

    Product Price
    Desktop Computer 700
    Tablet 250
    Printer 100
    Laptop 1200

    You may also want to check the following guides for other types of file conversions:

    Convert JSON to CSV in Python

    The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within . It is similar to the dictionary in Python.

    CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

    Converting JSON to CSV

    For simple JSON data consisting of key and value pairs, keys will be headers for the CSV file and values the descriptive data.

    Example: Suppose the JSON file looks like this:

    We want to convert the above JSON to CSV file with key as headers.

    Экспорт файла JSON в CSV с помощью Python

    JSON – это аббревиатура от JavaScript Object Notation. Это исполняемый скрипт, который позволяет нам легко хранить и передавать данные с одной платформы на другую. Мы часто сталкиваемся с ситуациями, когда нам нужно удалить данные из определенных источников. Итак, какова форма вывода очищенных данных?

    Этот формат позволяет нам иметь данные в виде пар ключ-значение. Все данные хранятся в виде «строки» в формате значения ключа.

    Но что, если я хочу, чтобы эти данные в JSON отправлялись дальше в базу данных для манипуляций? Самое простое решение, которое приходит мне на ум, – это экспорт файла JSON в виде файла CSV.

    Итак, давайте теперь посмотрим на шаги, которые нам нужно выполнить, чтобы преобразовать и экспортировать файл JSON в формат CSV (значения, разделенные запятыми).

    1. Импорт библиотеки

    Чтобы работать с CSV-файлами, нам нужно импортировать встроенный модуль, доступный, как показано:

    2. Сохранить значения заголовков и столбцов в списке

    При работе с экспортом данных JSON в формат CSV для нас очень важно указать значения заголовков или имена столбцов для каждого столбца.

    Таким образом, мы создаем отдельный список и передаем ключевые теги в созданный список, как показано ниже:

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

    3. Передать путь к CSV-файлу

    Теперь пришло время открыть файл CSV и указать на него объект. Далее, мы используем функцию csv.DictWriter() для записи и экспорта данных JSON в форму CSV.

    Мы создаем экземпляр функции DictWriter(), а затем помещаем значения столбцов в файл CSV. В конце концов, мы должны экспортировать значения данных с помощью функции writerows(), как показано ниже.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *