zoukankan      html  css  js  c++  java
  • 模块讲解----json模块(跨平台的序列化与反序列化)

    一、json的特点

    1、只能处理简单的可序列化的对象;(字典,列表,元祖)
    2、json支持不同语言之间的数据交互;(python  -  go,python - java)
     
    二、使用场景
    1、玩游戏的时候存档和读取记录。
    2、虚拟机挂起、保存或者恢复、读档的时候。
     
     
    三、语法:
    1、简单的数据类型:
     1 1、在内存中进行转换:
     2 import json
     3 #py基本数据类型转换字符串:
     4 r = json.dumps([11,22,33])
     5 #li = '["alex","eric"]'
     6 li = "['alex','eric']"
     7 re = json.loads(li)   #反序列化的时候,一定要使用双引号""。
     8 print(re,type(re))
     9 
    10 
    11 2、在文件中转换:(在dumps和loads基础上增加了个写读文件)
    12 import json
    13 
    14 文件格式的序列化:
    15 li = [11,22,33]
    16 json.dump(li,open('db','w'))
    17 
    18 
    19 文件格式的反序列化:
    20 li = json.load(open('db','r'))
    21 print(li,type(li))

    2、复杂的数据类型:

    序列化:

     1 #!/usr/bin/env python
     2 # -*- coding:utf8 -*-
     3 # Author:Dong Ye
     4 
     5 import json
     6 
     7 
     8 test = r'test.txt'
     9 
    10 info  = {
    11     'name' : 'alex',
    12     'age' : 32
    13 
    14 }
    15 
    16 with open(test,'w',encoding='utf-8') as f:
    17     f.write( json.dumps(info) )

    反序列化:

     1 #!/usr/bin/env python
     2 # -*- coding:utf8 -*-
     3 # Author:Dong Ye
     4 
     5 import  json
     6 
     7 test = r'test.txt'
     8 
     9 with open(test,'r',encoding='utf-8') as f:
    10     data = json.loads( f.read() )
    11     print(data)
    12     print(data['name'])
    13     print(data['age'])

    使用场景

    调用其他平台的接口时,一般都会返回一个字符串,eg:“字典,列表,url路径等”。
    1 import requests
    2 import json
    3 
    4 response = requests.get("http://http://wthrcdn.etouch.cn/weather_mini?ciyp=北京")
    5 response.encoding = 'utf-8'
    6 
    7 dic = json.loads(requests.text)
    8 print(response,type(response))
  • 相关阅读:
    1052 Linked List Sorting (25 分)
    1051 Pop Sequence (25 分)
    1050 String Subtraction (20 分)
    1049 Counting Ones (30 分)
    1048 Find Coins (25 分)
    1047 Student List for Course (25 分)
    1046 Shortest Distance (20 分)
    1045 Favorite Color Stripe (30 分)
    1044 Shopping in Mars (25 分)
    1055 The World's Richest (25 分)
  • 原文地址:https://www.cnblogs.com/abobo/p/8075251.html
Copyright © 2011-2022 走看看