在Python中使用JSON数据经典指南

2021年3月12日14:22:24 发表评论 646 次浏览

Python中JSON的介绍:

JSON的完整形式是JavaScript Object Notation。这意味着将使用编程语言的文本组成的脚本(可执行)文件用于存储和传输数据。 Python通过称为的内置程序包支持JSON

JSON

。要使用此功能, 我们以Python脚本导入json包。 JSON中的文本是通过带引号的字符串完成的, 该字符串包含内部的键-值映射中的值

{}

。它类似于Python中的字典。 JSON显示的API与标准库编组和pickle模块的用户相似, Python本身支持JSON功能。例如

# Python program showing 
# use of json package
  
import json
  
# {key:value mapping}
a = { "name" : "John" , "age" : 31 , "Salary" : 25000 }
  
# conversion to JSON done by dumps() function
  b = json.dumps(a)
  
# printing the output
print (b)

输出如下:

{"age": 31, "Salary": 25000, "name": "John"}

如你所见, JSON支持基本类型, 例如字符串和数字, 以及嵌套列表, 元组和对象

# Python program showing that
# json support different primitive
# types
  
import json
  
# list conversion to Array
print (json.dumps([ 'Welcome' , "to" , "lsbin" ]))
  
# tuple conversion to Array
print (json.dumps(( "Welcome" , "to" , "lsbin" )))
  
# string conversion to String
print (json.dumps( "Hi" ))
  
# int conversion to Number
print (json.dumps( 123 ))
  
# float conversion to Number
print (json.dumps( 23.572 ))
  
# Boolean conversion to their respective values
print (json.dumps( True ))
print (json.dumps( False ))
  
# None value to null
print (json.dumps( None ))

输出如下:

["Welcome", "to", "lsbin"]
["Welcome", "to", "lsbin"]
"Hi"
123
23.572
true
false
null

序列化JSON:

JSON编码过程通常称为

序列化

。该术语指的是将数据转换为一系列字节(因此称为串行)以在网络上存储或传输。为了处理文件中的数据流, Python中的JSON库使用

倾倒()

函数将Python对象转换为它们各自的JSON对象, 因此可以轻松地将数据写入文件。参见下表。

Python对象 JSON对象
字典 Object
列表, 元组 Array
str String
整数, 长, 浮点数 数字
true true
false false
None null

序列化示例:

考虑给定的Python对象示例。

var = { 
       "Subjects" : {
                   "Maths" : 85 , "Physics" : 90
                    }
       }

使用Python的上下文管理器上下文管理器, 创建一个名为Sample.json并以写入模式打开它。

with open ( "Sample.json" , "w" ) as p:
      json.dumps(var, p)

在这里

dumps()

首先接受两个参数, 一个是要序列化的数据对象, 第二个是将要写入的数据对象(字节格式)。

反序列化JSON:

反序列化与序列化相反, 即将JSON对象转换为它们各自的Python对象。的

加载()

方法用于它。如果你使用过其他程序的Json数据或以Json的字符串格式获取, 则可以使用以下命令轻松反序列化

加载()

, 通常用于从字符串加载, 否则, 根对象位于list或dict中。

with open ( "Sample.json" , "r" ) as read_it:
      data = json.load(read_it)

反序列化示例:

json_var = """
{
     "Country": {
         "name": "INDIA", "Languages_spoken": [
             {
                 "names": ["Hindi", "English", "Bengali", "Telugu"]
             }
         ]
     }
}
"""
var = json.loads(json_var)

编码和解码:

编码定义为将文本或值转换为只能由所需用户通过对其进行解码使用的加密形式。此处, 编码和解码是针对JSON(对象)格式进行的。编码也称为序列化, 而解码则称为反序列化。 Python有一个流行的软件包用于此操作。这个包被称为

Demjson

。要安装它, 请按照以下步骤操作。

对于Windows

pip install demjson

对于Ubuntu

sudo apt-get update
 sudo apt-get install python-demjson

编码方式:编码()函数用于将python对象转换为JSON字符串表示形式。句法

demjson.encode(self, obj, nest_level=0)

代码1:使用demjson包进行编码

# storing marks of 3 subjects
var = [{ "Math" : 50 , "physics" : 60 , "Chemistry" : 70 }]
print (demjson.encode(var))

输出如下:

[{"Chemistry":70, "Math":50, "physics":60}]

解码

解码()

函数用于将JSON对象转换为python格式类型。句法

demjson.decode(self, obj)

代码2:使用demjson包解码

var = '{"a":0, "b":1, "c":2, "d":3, "e":4}'
text = demjson.decode(var)

输出如下:

{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

代码3:使用iterencode包进行编码

# Other Method of Encoding
json.JSONEncoder().encode({ "foo" : [ "bar" ]})
'{"foo": ["bar"]}'
  
# Using iterencode(object) to encode a given object.
for i in json.JSONEncoder().iterencode(bigobject):
     mysocket.write(i)

代码4:

编码和解码使用

dumps()

负载()

# To encode and decode operations
import json
var = { 'age' : 31 , 'height' = 6 }
x = json.dumps(var)
y = json.loads(var)
print (x)
print (y)
  
# when performing from a file in disk
with open ( "any_file.json" , "r" ) as readit:
     x = json.load(readit)
print (x)

真实示例:

让我们以python中的JSON实现为例。练习目的的良好来源是

JSON_placeholder

, 它提供了很棒的API请求包, 我们将在示例中使用该包。首先, 请按照以下简单步骤操作。打开Python IDE或CLI并创建一个新的脚本文件, 将其命名为sample.py。

import requests
import json
  
# Now we have to request our JSON data through
# the API package
res = requests.get( "https://jsonplaceholder.typicode.com / todos" )
var = json.loads(res.text)
  
# To view your Json data, type var and hit enter
var
  
# Now our Goal is to find the User who have 
# maximum completed their task !!
# i.e we would count the True value of a 
# User in completed key.
# {
     # "userId": 1, # "id": 1, # "title": "Hey", # "completed": false, # we will count
                            # this for a user.
# }
  
# Note that there are multiple users with 
# unique id, and their task have respective
# Boolean Values.
  
def find(todo):
     check = todo[ "completed" ]
     max_var = todo[ "userId" ] in users
     return check and max_var
  
# To find the values.
  
Value = list ( filter (find, todos))
  
# To write these value to your disk
  
with open ( "sample.json" , "w" ) as data:
     Value = list ( filter (keep, todos))
     json.dump(Value, data, indent = 2 )

要了解更多, 点击这里

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: