Featured Post

15 Python Tips : How to Write Code Effectively

Image
 Here are some Python tips to keep in mind that will help you write clean, efficient, and bug-free code.     Python Tips for Effective Coding 1. Code Readability and PEP 8  Always aim for clean and readable code by following PEP 8 guidelines.  Use meaningful variable names, avoid excessively long lines (stick to 79 characters), and organize imports properly. 2. Use List Comprehensions List comprehensions are concise and often faster than regular for-loops. Example: squares = [x**2 for x in range(10)] instead of creating an empty list and appending each square value. 3. Take Advantage of Python’s Built-in Libraries  Libraries like itertools, collections, math, and datetime provide powerful functions and data structures that can simplify your code.   For example, collections.Counter can quickly count elements in a list, and itertools.chain can flatten nested lists. 4. Use enumerate Instead of Range     When you need both the index and the value in a loop, enumerate is a more Pyth

Python Program: JSON to CSV Conversion

JavaScript object notion is also called JSON file, it's data you can write to a CSV file. Here's a sample python logic for your ready reference. 




You can write a simple python program by importing the JSON, and CSV packages. This is your first step. It is helpful to use all the JSON methods in your python logic. That means the required package is JSON.

So far, so good. In the next step, I'll show you how to write a Python program. You'll also find each term explained.


What is JSON File

JSON is key value pair file. The popular use of JSON file is to transmit data between heterogeneous applications. Python supports JSON file.


What is CSV File

The CSV is comma separated file. It is popularly used to send and receive data.


How to Write JSON file data to a CSV file

Here the JSON data that has written to CSV file. It's simple method and you can use for CSV file conversion use.

import csv, json

json_string = '[{"value1": 1, "value2": 2,"value3": 1.234}]'
data = json.loads(json_string)
headers = data[0].keys()

with open('sample.csv', 'w') as f:
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
writer.writerows(data)


with open('sample.csv', 'r') as f:
    print(f)
    for row in f:
        print(row)

Output:

<_io.TextIOWrapper name='file.csv' mode='r' encoding='UTF-8'>
value1,value2,value3

1,2,1.234


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Conclusion

The output CSV file has both headers and rows, and the data is comma seprated.


References

Comments

Popular posts from this blog

How to Fix datetime Import Error in Python Quickly

SQL Query: 3 Methods for Calculating Cumulative SUM

Python placeholder '_' Perfect Way to Use it