当前位置:网站首页>JSON related
JSON related
2022-04-23 03:13:00 【A happy wild pointer D】
1、JSON Introduce
JSON:JavaScript Object Notation, namely JavaScript Object notation , Is a lightweight data exchange format , Independent of language , It can be read and used as data by any programming language .
JSON The values of can be of the following types :
- Numbers ( Integer or floating point )
- character string ( Must be enclosed in double quotation marks )
- Boolean value (true or false)
- Numbers ( Use square brackets to indicate )
- object ( In curly brackets )
- null
JSON There are two structural forms : Objects and arrays .
The object structure is {} Express , The middle contains 0 Or more key:value Yes , Data is passed through obj["key"] or obj.key How to get ;
Arrays are [] Express , In the middle by 0 Or a list of values , The data is orderly , therefore , It can be done by obj[index] To get data .
// 1. Object structure
var obj = {
"id":44021,
"name":" You know ",
"appPackage":"com.zhihu.android",
"size":23720,
"versionCode":442
};
console.log(obj.name);// You know
console.log(obj["name"]);// You know
// 2. Array structure
var obj = [
200,
"success",
{
"subCode":1,
"errorMsg":null
}
];
console.log(obj[0]);//200
console.log(obj[2].subCode);//1
2、 Application scenarios
(1) Interface returns data
- In the front and rear end separation system , The data transmitted from the back end to the front end
- Ajax Asynchronous access to data
- to open up API Interface , Such as Baidu translation 、 Weather information, etc
- The interface of cooperation between enterprises
...... wait
(2) serialize
serialize : Convert the object into a sequence of bytes that can be transferred ;
Deserialization : The process of restoring a byte sequence to an object
The ultimate purpose of serialization is to realize cross platform storage and network transmission , And our way of cross platform storage and network transmission is IO,IO The supported data is byte array .
JSON Is one of the common serialization methods . When the object is serialized , Will save class Information down , But the data types of different languages are different , It is possible that the serialized data cannot be restored to its original appearance . but JSON When serializing an object, only the attribute data of the object is saved , Will not save class Information , It can read and write data across languages .
another : We use some json Parsed Library , Such as java Of fastjson and python Of json library , Has helped us achieve serialization and deserialization , We don't have to write code explicitly .
(3) Generate Token
(4) The configuration file
The classic example is npm Package management profile for package.json
3、JSON Data operation
3.1 JavaScript
(1)eval()
This function takes a string parameter , And execute it as script code . such as :eval("{name:' Zhang San '}"),{} Is parsed into code blocks , Represents declaring an object . thus , Using this function will json Convert string to object , There are two ways :
The first one is : stay json Concatenate in front of the string "var obj = ";
The second kind : stay json Use before and after the string () Cover up , such eval Will not {} Parse into code blocks , It's an expression .
// The first way
var str = '{"id":"44021","name"," You know "}';
eval('var obj = ' + str);
console.log(obj["name"]);// You know
// The second way
var str = '{"id":"44021","name"," You know "}';
var obj = eval("(" + str + ")");
console.log(obj["name"]);// You know
(2)JSON.parse()
This function receives json Format string , Convert it to JavaScript object .
Special Usage : The function also has an argument reviver, It's a function , You can define some operations in it , Yes json The value of is processed and then returned .
var str = '{"id":"44021","name"," You know "}';
var obj = JSON.parse(str);
console.log(obj["name"]);// You know
var str = '[{"id":"44021","name"," You know "},{"id":"40019","name"," TaoBao "},{"id":"45001","name"," Public comment "}]';
var obj = JSON.parse(str);
console.log(obj[1].name);// TaoBao
// Special Usage
var text = '{"name":" Xiao Zhan ","birth":"1991-10-05","city":" Chongqing "}';
var obj = JSON.parse(text,function(key,value){
// Convert date string to date object
if (key == "birth"){
return new Date(value);
}else{
return value;
}
});
(3)JSON.stringify()
This function takes JavaScript Object to json character string : to key Parameters are enclosed in double quotes ,value unchanged .
var obj = {
name:" Wang Yibo ",
age:24,
city:" luoyang "
};
var jsonStr = JSON.stringify(obj);
console.log(jsonStr[1]);//"
3.2 Java
fastjson There are three main categories :JSON、JSONObject、JSONArray.
among ,JSON Is the parent of the other two classes , Mainly used for json String and object conversion , Including string and JavaBean、JSONObject、JSONArray The mutual transformation between them ; and JSONObject and JSONArray Is used for parsing json character string 、 get data .
(1)JSON
// json String to javabean
String str = "{\"format\":\"png\",\"leval\":1,\"title\":\"json String to javabean\"}";
Material m = JSON.parseObject(str,Material.class);
// json String to list
String str = "[{\"format\":\"png\",\"leval\":1,\"title\":\" First object \"},{\"format\":\"jpg\",\"leval\":2,\"title\":\" The second object \"},{\"format\":\"gif\",\"leval\":3,\"title\":\" The third object \"}]";
List<Material> materials = JSON.parseArray(str,Material.class);
for (Material m : materials)
{
System.out.println(m.toString);
}
// jsonobject To javabean
// jaonarray To list
JSONArray mUrls = item.getJSONArray("mUrls");
for (int i = 0; i < mUrls.size(); i++)
{
MUrl url = JSON.toJavaObject(mUrls.getJSONObject(i),MUrl.class);
list.add(url);
}
// map To json character string
ArrayList<Material> list = new ArrayList<>();
list.add(material);
list.add(material2);
list.add(material3);
HashMap<String,Object> map = new HashMap<>();
map.put("leval",1);
map.put("title","map To json character string ");
map.put("list",list);
map.put("format","png");
System.out.println(JSON.toJSONString(map));
(2)JSONObject
getxxx(key): obtain key Corresponding value , And turn it into a certain type , Such as getInteger()、getString、getJSONArray() etc. .
String msg = (String)jsonObject.get("msg");
Integer code = jsonObject.getInteger("code");
JsonArray objects = jsonObject.getJSONArray("objects");
(3)JSONArray
And JSONObject be similar , Data is also obtained through getxxx(index) The way , It's just that the parameter is the index index.
in addition , because JSONArray It stands for json An array of objects , Class also provides direct operations json Object method , Such as add()、remove() etc. .
3.3 Python
版权声明
本文为[A happy wild pointer D]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220627537908.html
边栏推荐
- 2022 Shandong Province safety officer C certificate work certificate question bank and online simulation examination
- 在.NE6 WebApi中使用分布式缓存Redis
- C# 读写二进制文件
- 一套组合拳,打造一款 IDEA 护眼方案
- 【VS Code】解决jupyter文件在vs code中显示异常的问题
- 建立与遍历二叉树
- The most understandable life cycle of dependency injection
- How does Microsoft solve the problem of multiple PC programs
- Test experience data
- 队列的存储和循环队列
猜你喜欢

2022山东省安全员C证上岗证题库及在线模拟考试

一套组合拳,打造一款 IDEA 护眼方案

全网最全,接口自动化测试怎么做的?精通接口自动化测试详解

The backtracking of stack is used to solve the problem of "the longest absolute path of file"

The most easy to understand dependency injection and control inversion

LoadRunner - performance testing tool

Blazor University (11) component - replace attributes of subcomponents

微软是如何解决 PC 端程序多开问题的

手机连接电脑后,QT的QDIR怎么读取手机文件路径

2022 P cylinder filling training test questions and simulation test
随机推荐
ASP. Net 6 middleware series - conditional Middleware
What kind of experience is it to prepare for a month to participate in ACM?
[MySQL] left function | right function
2022g2 boiler stoker examination question bank and online simulation examination
First in the binary tree
Mise en service PID du moteur de codage (anneau de vitesse | anneau de position | suivant)
宁德时代地位不保?
Vs code setting line feed
一文了解全面静态代码分析
ASP. Net 6 middleware series - execution sequence
. net core current limiting control - aspnetcoreratelimit
Source generator actual combat
可以接收多种数据类型参数——可变参数
C language to achieve address book - (static version)
Drawing polygons with < polygon / > circular array in SVG tag
Impact of AOT and single file release on program performance
2022年度Top9的任务管理系统
Tips in MATLAB
全网最全,接口自动化测试怎么做的?精通接口自动化测试详解
MAUI初体验:爽