当前位置:网站首页>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
边栏推荐
- js递归树结构计算每个节点的叶子节点的数量并且输出
- 建立与遍历二叉树
- Judge whether there is a leap year in the given year
- Top 9 task management system in 2022
- 队列的存储和循环队列
- 再战leetcode (290.单词规律)
- Use DFS to solve the problem of "number of dictionary rows"
- ASP.NET 6 中间件系列 - 自定义中间件类
- be based on. NETCORE development blog project starblog - (1) why do you need to write your own blog?
- Xamarin effect Chapter 21 expandable floating operation button in GIS
猜你喜欢
Xutils3 corrected a bug I reported. Happy
Tencent video price rise: earn more than 7.4 billion a year! Pay attention to me to receive Tencent VIP members, and the weekly card is as low as 7 yuan
The most easy to understand dependency injection and control inversion
一套组合拳,打造一款 IDEA 护眼方案
OLED multi-level menu record
[Mysql] LEFT函数 | RIGHT函数
C language to achieve address book - (static version)
Vs code setting line feed
Tencent video VIP member, weekly card special price of 9 yuan! Tencent official direct charging, members take effect immediately!
Fight leetcode again (290. Word law)
随机推荐
12.<tag-链表和常考点综合>-lt.234-回文链表
先中二叉建树
Tips in MATLAB
【鉴权/授权】自定义一个身份认证Handler
类似Jira的十大项目管理软件
中后二叉建树
软件测试相关知识~
C language to achieve address book - (static version)
Distributed system services
【新版发布】ComponentOne 新增 .NET 6 和 Blazor 平台控件支持
Xutils3 corrected a bug I reported. Happy
What kind of experience is it to prepare for a month to participate in ACM?
[Mysql] LEFT函數 | RIGHT函數
Laravel new route file
Flink实时数仓项目—DWS层设计与实现
IOTOS物联中台对接海康安防平台(iSecure Center)门禁系统
The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details
ASP. Net 6 middleware series - conditional Middleware
LNMP MySQL allows remote access
Ningde's position in the times is not guaranteed?