JSON数据格式详解
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",}}*/intmain(intargc,char*argv[]){//首先建一个空的Objectjson_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//嵌套一个Objectjson_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//编码成stringtext指向这个字符串内存地址char*text=NULL;json_tree_to_string(root,&text);//释放这个rootprintf("jsonendcode:\n%s\n",text);//json字符串变成json对象数读jsonjson_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;//获取valueprintf("nametype%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("nametype%d:%s\n",arrat1->type,arrat1->text);//获取数组下一个nextjson_t*arrat2=arrat1->next;printf("nametype%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("nametype%d:%s\n",arrat2->type,arrat2->text);//还有在释放一次因为这个是生成的对象数json_free_value(&root);system("pause");return0;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。