python-json解析

在python编程中经常用到json库来对json串进行解码和编码解析,现将之间的转换整理如下:

  • json.dumps
    将python对象编码成json字符串, 返回json串

  • json.loads
    将已编码的json串解码为python对象,返回python对应的数据类型

代码

#-*- coding:utf-8 -*-
#__author__='yy'
import json
if __name__=="__main__":
   '''
    print("json转dict")
    json_str='{"name":"开源优测","url":"www.testingunion","id":"DeepTest"}'
    #原类型
    print("原类型:",type(json_str))
    #转换成dict对象
    json_dict = json.loads(json_str)
    print("转换后的类型:",type(json_dict))
    #遍历
    for(k,v) in json_dict.items():
        print(k,":",v)



    print("字典型转json串")
    json_dict = {
        "name":"开源优测",
        "url":"www.testingunion.com",
        "id":"DeepTest"
    }
    print("原类型:",type(json_dict))
    json_str = json.dumps(json_dict)

    print("转换后类型:",type(json_str))
    print(json_str)
   '''
   print("json串解析实例")
   json_demo = """     #用单引号,双引号,三引号引起来的就是字符串 
        {
            "App":[
                {
                    "name": "test01",
                    "uid": "DeepTest",
                    "desc": "分享技术"
                },
                {
                    "name": "test01_demo",
                    "uid": "DeepTest_demo",
                    "desc": "分享技术_demo"
                }
            ],
            "web": [
                {
                    "url": "www.testingunion.com",
                    "name": "开源优测社区",
                    "desc": "分享各类开源优测技巧"
                },
                {
                    "url": "www.testinggunion.com_demo",
                    "name": "开源优测社区_demo",
                    "desc": "分享各类开源测试技巧_demo"
                }
            ]
         }
    """
    #将json串转换成字典
   json_dict = json.loads(json_demo)
    #遍历字典
   for (k, v) in json_dict.items():
        #输出第一层级,k为weixin、web;v为其对应的列表即[]中的数据
        print(k,":",v)
        for data in v:
            #遍历列表
            #v为[]
            for (data_k,data_v) in data.items():
                #遍历列表中的字典
                print("  ",data_k,":",data_v)


备注:以上整理来自苦叶子“开源优测”公众号python系列

你可能感兴趣的:(python-json解析)