温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JSON数据格式详解

发布时间:2020-07-20 11:42:45 来源:网络 阅读:4067 作者:超级极客 栏目:编程语言

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


#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;
}






向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI