How to use Python to process JSON data? This article will introduce you to the basic methods of using Python to process JSON data. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Before introducing the basic methods of using Python to process JSON data, we must first understandWhat is JSON?
JSON stands for "JavaScript Object Notation", which can be said to be a "data format based on JavaScript language symbols". However, this notation is only based on JavaScript and can be used in various other languages.
JSON is a way we store and exchange data, implemented through its syntax, and used in many web applications. The advantage of JSON is that it has a human-readable format, which may be one of the reasons for using it in data transfer, in addition to its effectiveness when using APIs.
In JSON, data is represented by name/value pairs; objects are stored within curly brackets, each name is followed by ':' (colon), and name/value pairs are separated by (comma ) separated; square brackets enclose the array, with values separated by (comma).
Example of JSON format data:
{ "book1":{ "title": "Python Beginners", "year": 2005 , "page": 399 }, "book2":{ "title": "Python Developers", "year": 2006 , "page": 650 } }
Let’s take a closer look at how to process JSON data in Python.
Python makes processing JSON data easy. The module that achieves this is the json module. This module should be included in the Python (built-in) installation, so you don't need to install any external modules like you do with PDF and Excel files. To use this module, the only thing you need is to import it (start by writing):
import json
But what does the JSON library do? This library mainly parses JSON from files or strings. It also parses JSON to dictionary or list in Python and vice versa i.e. converts Python dictionary or list to JSON string.
Reading JSON (JSON to Python)
Reading JSON means converting JSON to Python values (objects). As mentioned above, the json library parses JSON into a dictionary or list in Python. For this we use loads() function (load from string) as shown below:
import json jsonData = '{"name": "Frank", "age": 39}' jsonToPython = json.loads(jsonData)
If you want to see the output, do print jsonToPython, in this case you will get the following output:
{'age': 39, 'name': 'Frank'}
That is, the data is returned as a Python dictionary (JSON object data structure).
Python to JSON
In the previous section we introduced JSON to Python, in this section we will show you how to convert Python values (encoded) as JSON.
Suppose we have the following dictionary in Python:
import json pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True} dictionaryToJson = json.dumps(pythonDictionary)
If we run print dictionaryToJson, we get the following JSON data:
{"age": 44, "isEmployed": true, "name": "Bob"}
Therefore, this output is treated as an object ( Dictionary) data representation. The method dumps() is the key to this type of operation.
It should be noted at this time that JSON cannot store all types of Python objects, and can only store the following types: List; Dictionary; Boolean value; Number; String; None. Therefore, any other types need to be converted for storage in JSON.
Suppose we have the following class:
class Employee(object): def __init__(self, name): self.name = name
Suppose we create a new object abder as follows:
abder = Employee('Abder')
If we want to convert this object to JSON, the what to do? Is that json.dumps(abder)? In this case, you will receive an error similar to the following:
Traceback (most recent call last): File "test.py", line 8, in <module> abderJson = json.dumps(abder) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps return _default_encoder.encode(obj) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: <__main__.Employee object at 0x10e74b750> is not JSON serializable
But, is there a workaround? Fortunately there is. To solve this problem, we can define a method similar to the following:
def jsonDefault(object): return object.__dict__
Then encode the object to JSON like this:
jsonAbder = json.dumps(abder, default=jsonDefault)
If you run print jsonAbder, you should get the following output :
{"name": "Abder"}
We have now encoded the Python object (abder) to JSON.
The above is the detailed content of How to process JSON data using Python. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!
