JSON usage scenarios and precautions introduced

The first part we explain the reason for the birth of XML because JSON is integrated into the details of HTML in various browser implementations vary, so Douglas Crockford (Douglas Crockford) and Chip Mourning Star (Chip Morningstar) together JS extracted from the data type in a subset of, as new data exchange format because the mainstream browser to use a common JavaScript engine components, so there is no compatibility issues when parsing new data format, so they this data format will be named as "JavaScript Object Notation", abbreviated to JSON, JSON thus was born!

Today we learn about the structure of JSON data type, usage scenarios and notes it!

A, JSON format

Above we know that a subset of JSON is extracted from the data type in JavaScript, JSON there are several structures that form it? What data types have it? What they correspond to the data type in JavaScript it?

Two kinds of structure 1.JSON

1, in the form of key-value pairs

Last issue we gave a JSON instance, it is in the form of key-value pairs, as follows:

{
  "person": {
    "name": "pig",
    "age": "18",
    "sex": "man",
    "hometown": {
      "province": "江西省",
      "city": "抚州市",
      "county": "崇仁县"
    }
  }
}

JSON data structure such rules are: a disordered "name / value pairs" collection. A left parenthesis {objects beginning, end} right parenthesis. Each "name" followed by a: colon; "" name / value pairs "used between, separated by commas .
Here Insert Picture Description
2, an array
because most of the time we used JSON may have been the kind of key-value in the form above, so a lot of people at the time to explain the JSON always ignores an array, they are to be noted.

That array of JSON is kind of how it? Gentlemen also give an example of it!

["pig", 18, "man", "江西省抚州市崇仁县"]

JSON data in the form of an array is the value (value) of the ordered set. An array with [left bracket begins] ending right bracket. Use between values separated by commas.
Here Insert Picture Description

Six types of data 2.JOSN

上面两种JSON形式内部都是包含value的,那JSON的value到底有哪些类型,而且上期我们说JSON其实就是从Js数据格式中提取了一个子集,那具体有哪几种数据类型呢?

  1. string:字符串,必须要用双引号引起来。
  2. number:数值,与JavaScript的number一致,整数(不使用小数点或指数计数法)最多为 15 位。小数的最大位数是 17
  3. object:JavaScript的对象形式,{ key:value }表示方式,可嵌套。
  4. array:数组,JavaScript的Array表示方式[ value ],可嵌套。
  5. true/false:布尔类型,JavaScript的boolean类型。
  6. null:空值,JavaScript的null。

Here Insert Picture Description
以上数据形式图片来源JSON官方文档:http://www.json.org/json-zh.html

二、JSON使用场景

介绍完JSON的数据格式,那我们来看看JSON在企业中使用的比较多的场景。

1.接口返回数据

JSON用的最多的地方莫过于Web了,现在的数据接口基本上都是返回的JSON,具体细化的场景有:

  1. Ajxa异步访问数据
  2. RPC远程调用
  3. 前后端分离后端返回的数据
  4. 开放API,如百度、高德等一些开放接口
  5. 企业间合作接口

这种API接口一般都会提供一个接口文档,说明接口的入参、出参等,
Here Insert Picture Description
一般的接口返回数据都会封装成JSON格式,比如类似下面这种

{
    "code": 1,
    "msg": "success",
    "data": {
        "name": "pig",
        "age": "18",
        "sex": "man",
        "hometown": {
            "province": "江西省",
            "city": "抚州市",
            "county": "崇仁县"
        }
    }
}

2.序列化

程序在运行时所有的变量都是保存在内存当中的,如果出现程序重启或者机器宕机的情况,那这些数据就丢失了。一般情况运行时变量并不是那么重要丢了就丢了,但有些内存中的数据是需要保存起来供下次程序或者其他程序使用。

保存内存中的数据要么保存在数据库,要么保存直接到文件中,而将内存中的数据变成可保存或可传输的数据的过程叫做序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。

正常的序列化是将编程语言中的对象直接转成可保存或可传输的,这样会保存对象的类型信息,而JSON序列化则不会保留对象类型!

为了让大家更直观的感受区别,猪哥用代码做一个测试,大家一目了然
Here Insert Picture Description

  1. Python对象直接序列化会保存class信息,下次使用loads加载到内存时直接变成Python对象。
  2. JSON对象序列化只保存属性数据,不保留class信息,下次使用loads加载到内存可以直接转成dict对象,当然也可以转为Person对象,但是需要写辅助方法。

对于JSON序列化不能保存class信息的特点,那JSON序列化还有什么用?答案是当然游有用,对于不同编程语言序列化读取有用,比如:我用Python爬取数据然后转成对象,现在我需要将它序列化磁盘,然后使用Java语言读取这份数据,这个时候由于跨语言数据类型不同,所以就需要用到JSON序列化。

存在即合理,两种序列化可根据需求自行选择!

3.生成Token

首先声明Token的形式多种多样,有JSON、字符串、数字等等,只要能满足需求即可,没有规定用哪种形式。

JSON格式的Token最有代表性的莫过于JWT(JSON Web Tokens)。
Here Insert Picture Description
随着技术的发展,分布式web应用的普及,通过Session管理用户登录状态成本越来越高,因此慢慢发展成为Token的方式做登录身份校验,然后通过Token去取Redis中的缓存的用户信息,随着之后JWT的出现,校验方式更加简单便捷化,无需通过Redis缓存,而是直接根据Token取出保存的用户信息,以及对Token可用性校验,单点登录更为简单。
Here Insert Picture Description
猪哥也曾经使用JWT做过app的登录系统,大概的流程就是:

  1. 用户输入用户名密码
  2. app请求登录中心验证用户名密码
  3. 如果验证通过则生成一个Token,其中Token中包含:用户的uid、Token过期时间、过期延期时间等,然后返回给app
  4. app获得Token,保存在cookie中,下次请求其他服务则带上
  5. 其他服务获取到Token之后调用登录中心接口验证
  6. 验证通过则响应

JWT登录认证有哪些优势:

  1. 性能好:服务器不需要保存大量的session
  2. 单点登录(登录一个应用,同一个企业的其他应用都可以访问):使用JWT做一个登录中心基本搞定,很容易实现。
  3. 兼容性好:支持移动设备,支持跨程序调用,Cookie 是不允许垮域访问的,而 Token 则不存在这个问题。
  4. 安全性好:因为有签名,所以JWT可以防止被篡改。

更多JWT相关知识自行在网上学习,本文不过多介绍!

4.配置文件

说实话JSON作为配置文件使用场景并不多,最具代表性的就是npm的package.json包管理配置文件了,下面就是一个npm的package.json配置文件内容。

{
  "name": "server",       //项目名称
  "version": "0.0.0",
  "private": true,
  "main": "server.js",   //项目入口地址,即执行npm后会执行的项目
  "scripts": {
    "start": "node ./bin/www"  ///scripts指定了运行脚本命令的npm命令行缩写
  },
  "dependencies": {
    "cookie-parser": "~1.4.3",  //指定项目开发所需的模块
    "debug": "~2.6.9",
    "express": "~4.16.0",
    "http-errors": "~1.6.2",
    "jade": "~1.11.0",
    "morgan": "~1.9.0"
  }
}

但其实JSON并不合适做配置文件,因为它不能写注释、作为配置文件的可读性差等原因。

配置文件的格式有很多种如:toml、yaml、xml、ini等,目前很多地方开始使用yaml作为配置文件。

三、JSON在Python中的使用

最后我们来看看Python中操作JSON的方法有哪些,在Python中操作JSON时需要引入json标准库。

import json

1.类型转换

1、Python类型转JSON:json.dump()

# 1、Python的dict类型转JSON
person_dict = {'name': 'pig', 'age': 18, 'sex': 'man', 'hometown': '江西抚州'}
# indent参数为缩进空格数
person_dict_json = json.dumps(person_dict, indent=4)
print(person_dict_json, '\n')

# 2、Python的列表类型转JSON
person_list = ['pig', 18, 'man', '江西抚州']
person_list_json = json.dumps(person_list)
print(person_list_json, '\n')

# 3、Python的对象类型转JSON
person_obj = Person('pig', 18, 'man', '江西抚州')
# 中间的匿名函数是获得对象所有属性的字典形式
person_obj_json = json.dumps(person_obj, default=lambda obj: obj.__dict__, indent=4)
print(person_obj_json, '\n')

执行结果:
Here Insert Picture Description

2、JSON转Python类型:json.loads()

# 4、JSON转Python的dict类型
person_json = '{ "name": "pig","age": 18, "sex": "man", "hometown": "江西抚州"}'
person_json_dict = json.loads(person_json)
print(type(person_json_dict), '\n')

# 5、JSON转Python的列表类型
person_json2 = '["pig", 18, "man", "江西抚州"]'
person_json_list = json.loads(person_json2)
print(type(person_json_list), '\n')

# 6、JSON转Python的自定义对象类型
person_json = '{ "name": "pig","age": 18, "sex": "man", "hometown": "江西抚州"}'
# object_hook参数是将dict对象转成自定义对象
person_json_obj = json.loads(person_json, object_hook=lambda d: Person(d['name'], d['age'], d['sex'], d['hometown']))
print(type(person_json_obj), '\n')

执行结果如下:
Here Insert Picture Description

2.对应的数据类型

上面我们演示了Python类型与JSON的相互转换,最开始的时候我们讲过JSON有6种数据类型,那这6种数据类型分别对应Python中的哪些数据类型呢?
Here Insert Picture Description

3.需要注意的点

  1. JSON的键名和字符串都必须使用双引号引起来,而Python中单引号也可以表示为字符串,所以这是个比较容易犯的错误!
  2. Python类型与JSON相互转换的时候到底是用load/dump还是用loads\dumps?他们之间有什么区别?什么时候该加s什么时候不该加s?这个我们可以通过查看源码找到答案:不加s的方法入参多了一个fp表示filepath,最后多了一个写入文件的操作。所以我们在记忆的时候可以这样记忆:s表示转成字符串(str),不加s表示转成文件。Here Insert Picture Description
  3. Python自定义对象与JSON相互转换的时候需要辅助方法来指明属性与键名的对应关系,如果不指定一个方法则会抛出异常!
    Here Insert Picture Description
  4. 相信有些看的仔细的同学会好奇上面猪哥使用json.dumps方法将Python类型转JSON的时候,如果出现中文,则会出现:\u6c5f\u897f\u629a\u5dde这种东西,这是为什么呢?原因是:Python 3中的json在做dumps操作时,会将中文转换成unicode编码,并以16进制方式存储,而并不是UTF-8格式!

四、总结

Today we learned two forms of JSON, JSON also remember [...]this form.

Learn six types of JSON data types for Python in which they were.

JSON understand some usage scenarios and practical examples.

They also learned how to use JSON matters in Python and need attention.

Combined with the period of birth and development of the introduction JSON , JSON related to our basic knowledge on the introduction of similar, we will be back some reptiles actual cases to teach you how to parse the returned JSON data.

JSON knowledge but a two minute long article (ten thousand words) is concerned, its importance is self-evident. Because whether you are doing reptiles, or do data analysis, web, and even front-end, testing, operation and maintenance, JSON is you have to be a master of knowledge!

Guess you like

Origin www.cnblogs.com/pig66/p/11959035.html