Python3のjson格式数据的处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lixinging/article/details/89293675

一、引言

在自动化测试的时候经常遇到json格式数据的处理,也经常被周围想刚学习Python的同志问起这个,今天专门写一个短文介绍一下。

二、先说说json

现在json越来越流行,基本上称为主流,开发在做技术方案的时候也首选json做为数据交换的格式。各位测试的小伙伴也发现了,对于xml格式,json是比较易于阅读。反正总结起来就是json很多好处,运用很广泛,想学习自动化的小伙伴,不管是Python、Java还是Ruby,对于json数据的处理还是需要有掌握的。

三、Python的处理方式

先给一个测试的数据

{
  "name": "abc",
  "url": "http://www.abc.com",
  "page": 88,
  "isNonProfit": true,
  "address": {
    "street": "科技园路.",
    "city": "江苏苏州",
    "country": "中国"
  },
  "links": [
    {
      "name": "Google",
      "url": "http://www.google.com"
    },
    {
      "name": "Baidu",
      "url": "http://www.baidu.com"
    },
    {
      "name": "SoSo",
      "url": "http://www.SoSo.com"
    }
  ]
}

1. 直接解析json字符串

# -*- coding: utf-8 -*-
import json  # 一个Python3内置的模块不需要安装

json_str = '{"name":"abc","url":"http://www.abc.com","page":88,"isNonProfit":true,"address":{"street":"科技园路.","city":"江苏苏州","country":"中国"},"links":[{"name":"Google","url":"http://www.google.com"},{"name":"Baidu","url":"http://www.baidu.com"},{"name":"SoSo","url":"http://www.SoSo.com"}]}'
print('json_str的类型是:' + str(type(json_str)))
json_dict = json.loads(json_str)
print('json_dict的类型是:' + str(type(json_dict)))
print('name的值是:'+json_dict['name'])

我们直接使用json模块的loads方法,传入json格式的字符串,返回的是Python中的字典(dict)格式。之后我们可以使用字典的取值方式,获取各个key的值。
输出结果:

json_str的类型是:<class 'str'>
json_dict的类型是:<class 'dict'>
name的值是:abc

2. 解析json文件

我想将上面的json字符串的内容保存在了一个文件中json_file.json,与测试脚本放在一个目录下面。

# -*- coding: utf-8 -*-
import json  # 一个Python3内置的模块不需要安装

f = open(file='json_file.json', mode='r', encoding='utf-8')
json_dict = json.load(f)
print('json_dict的类型是:' + str(type(json_dict)))
print('name的值是:' + json_dict['name'])

先使用open函数打开一个文件,传到load方法中,其实看源码可以知道load方法还是调用了loads方法。
打印结果:

json_dict的类型是:<class 'dict'>
name的值是:abc

3. 字典数据转成json字符串

new_json_str = json.dumps(json_dict)

直接使用dumps函数就可以了

4. 字典数据转成json字符串,到文件

上面这个方法是将json字符串保存到变量中的,还有一个方法dump可以将字符串直接保存到文件。

f = open(file='new_json_file.json', mode='w', encoding='utf-8')
new_json_str = json.dump(json_dict,f,ensure_ascii=False)

ensure_ascii:控制是否转义中文,默认True,文件中的中文会保存成\u开头的编码。设置成False就会正确显示中文。

简书同步地址:https://www.jianshu.com/p/636b66ceecbd

猜你喜欢

转载自blog.csdn.net/lixinging/article/details/89293675
今日推荐