且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JSON数据格式详解

更新时间:2022-08-20 23:30:03

1json数据格式简介(JaveScript Object Notation)

随着JaveScript的流行和互联网应用,JavaScript里面最强大的

数据类型Object,使用起来及其方便,可以满足所有的数据存储.

为了能更好的做数据交换,设计了JSON协议,能够将JavaScript里面

的Object与Json的转换,Object对象转换成Json数据以后,方便

传输和存储,json变为Object方便对象重建.

Object又叫做表 存放的就是 key:value   name:小明

key可以是字符串和数据

value可以是数组,字符串,bool,数组多个value,object

JSON是完全独立于语言的文本格式,易于阅读与编写以及解析.



2使用c语言开源库mjson 解析json


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "mjson/json.h"
/*
{ //root
"k_num" : 123,
"k_str" : "hello",
"k_logic" : true,
"k_null" : null,
"k_array" : [1,"hello","2"],
"weap_object" : 
{
"default":"putongzidan",
}
}
*/
int main(int argc, char*argv[])
{
//首先建一个空的Object
json_t* root = json_new_object();
//new一个数字 //把这个元素 加到object里
json_t* k_num = json_new_number("123");
json_insert_pair_into_object(root,"k_num",k_num);
json_t* uname = json_new_string("hello");
json_insert_pair_into_object(root, "k_str", uname);
json_t* logic = json_new_true();
json_insert_pair_into_object(root, "k_logic", logic);
json_t* knull = json_new_null();
json_insert_pair_into_object(root, "k_null", knull);
//array 数组
json_t *man_array = json_new_array();
json_insert_pair_into_object(root, "k_array", man_array);
//给数组插入数组
json_t* tmp1 = json_new_number("1");
json_t* tmp2 = json_new_string("hello");
json_insert_child(man_array, tmp1);
json_insert_child(man_array, tmp2);
//end
//嵌套一个Object
json_t* weap_object = json_new_object();
json_insert_pair_into_object(root, "weap_object", weap_object);
//嵌套的object 里面在加元素
tmp1 = json_new_string("putongzidan");
json_insert_pair_into_object(weap_object, "default", tmp1);
//end
//编码成string   text指向这个字符串内存地址
char* text = NULL;
json_tree_to_string(root, &text);
//释放 这个root
printf("json endcode :\n%s\n",text);
//json字符串  变成json对象数 读json
json_free_value(&root);
root = NULL;
json_parse_document(&root,text);//从json文本来生成json对象数
free(text);
//解码这个字符串
json_t* user_name = json_find_first_label(root,"k_str");
json_t* user = user_name->child;//获取value
printf("name type%d:%s\n", user->type, user->text);
//解码array里的
json_t* user_array = json_find_first_label(root, "k_array");
json_t* arrat1 = user_array->child->child;
printf("name type%d:%s\n", arrat1->type, arrat1->text);
//获取数组 下一个next
json_t* arrat2 = arrat1->next;
printf("name type%d:%s\n", arrat2->type, arrat2->text);
//解码object里的
json_t* user_object = json_find_first_label(root, "weap_object");
json_t* user_object_child = user_object->child->child;
arrat2 = user_object_child->child;
printf("name type%d:%s\n", arrat2->type, arrat2->text);
//还有在释放一次  因为这个是 生成的对象数
json_free_value(&root);
system("pause");
return 0;
}



 本文转自超级极客51CTO博客,原文链接:http://blog.51cto.com/12158490/2059535,如需转载请自行联系原作者