C json是一種常用的數(shù)據(jù)交換格式,可以將數(shù)據(jù)序列化為json格式,然后傳輸?shù)巾?yè)面上進(jìn)行顯示。下面我們將介紹如何將C json格式的數(shù)據(jù)顯示到頁(yè)面上。
#include#include #include #include int main() { int i; char *str = "{\"name\":\"Jack\",\"age\":20,\"address\":{\"city\":\"New York\",\"state\":\"NY\"},\"hobby\":[\"reading\",\"playing games\"]}"; struct json_object *obj,*obj_name,*obj_age,*obj_address,*obj_city,*obj_state,*obj_hobby,*obj_hobby_item; obj = json_tokener_parse(str); json_object_object_get_ex(obj,"name",&obj_name); json_object_object_get_ex(obj,"age",&obj_age); json_object_object_get_ex(obj,"address",&obj_address); json_object_object_get_ex(obj_address,"city",&obj_city); json_object_object_get_ex(obj_address,"state",&obj_state); json_object_object_get_ex(obj,"hobby",&obj_hobby); printf("Name:%s\n",json_object_get_string(obj_name)); printf("Age:%d\n",json_object_get_int(obj_age)); printf("City:%s\n",json_object_get_string(obj_city)); printf("State:%s\n",json_object_get_string(obj_state)); printf("Hobby:\n"); for(i=0;i 以上代碼中,我們使用了json-c庫(kù)中的函數(shù)來(lái)解析C json格式的數(shù)據(jù),并將其顯示到控制臺(tái)上。這里我們通過(guò)json_tokener_parse函數(shù)將json格式的字符串進(jìn)行解析,然后使用json_object_object_get_ex函數(shù)獲取json對(duì)象中的值。最后,我們將獲取的數(shù)據(jù)使用printf函數(shù)輸出。
在實(shí)際應(yīng)用中,我們可以將獲取的數(shù)據(jù)用于頁(yè)面的顯示。這里我們可以使用Ajax技術(shù)從服務(wù)器端獲取C json格式的數(shù)據(jù),并將其顯示到頁(yè)面上。例如:
$.ajax({ url:'getjson.php', dataType:'json', success:function(data){ var str = 'Name:'+data.name+'
Age:'+data.age+'
City:'+data.address.city+'
State:'+data.address.state+'
Hobby:
'; $.each(data.hobby,function(index,item){ str += item+'
'; }); $('#info').html(str); } });以上代碼中,我們使用了jQuery框架中的$.ajax函數(shù)從服務(wù)器端獲取C json格式的數(shù)據(jù),并將其顯示到頁(yè)面上。這里我們使用了$.each函數(shù)遍歷了json對(duì)象中的值。