A JSON parsing and processing library written in C + +

Source: Internet
Author: User
Tags traits

 The following transfers are from: http://blog.csdn.net/ggicci/article/details/10600403

What is JSON? What can this library do?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It's Easy forHumans to read and write. Json is a lightweight data interchange format that is often used in WEB development as well as XML. In the Ajax application, the foreground basically uses JSON as the data Interchange format, because in the JS inside can through the Json.parse () function to parse the JSON format string to obtain the JS object, through this JS object can easily obtain and modifies the inside data. And this library Ggicci::json can get a similar C + + object by parsing like JS. With this C + + object, you can get and modify the data as you would with JS, essentially similar to the syntax. Just C + + is a strongly typed language, so you throw an exception when you try to get the value inside with a different data type. As to whether C + + needs a JSON parser, the answer is yes, such as a CS architecture of the program, the server side has some pages using Web technology to output JSON data, the client is a C + + client, which sends HTTP requests to these pages and receives JSON data, the data need to parse To match the client's use. Unless, of course, the client simply outputs these strings or the client uses the C + +With JS mixed programming way, let JS to process the data.project address and documentationGithub:https://github.com/ggicci/ggicci--jsonggicci:http://ggicci.me/works/json Document: Http://ggicci.me/works/json/docSee a simple example#include <iostream>#include "Gci-json.h" using namespaceStd Using namespaceGgicci; int main (int argc, Char const *Argv[]) {//Parse a string to get a JSON object JSON JSON = JSON::P arse ("{\ \" id\ ": 18293, \ \" name\ ": \" ggicci\ ", \ \" b Irthday\ ": [1991, one, ten], \ \" man\ ": true \}");cout << "JSON =" << json <<Endl cout << "-----------------------" <<Endl cout << "ID:" << json["id"] <<Endl cout << "Name:" << json["name"] <<Endl cout << "birthday-year:" << json["Birthday"][0] <<Endl cout << "Birthday-month:" << json["Birthday"][1] <<Endl cout << "Birthday-day:" << json["Birthday"][2] <<Endl cout << "man:" << boolalpha << json["man" <<Endl cout << "-----------------------" <<Endl json["name"] = "Mingjie Tang"; Add Property:method 1 json["school"] = "Northwest A&f University";//Add Property:method 2 json. AddProperty ("Traits", Json::P arse ("[]"). Push ("sympathetic"). Push ("Independent" )); cout << "JSON =" << json << Endl; cout << "-----------------------" << Endl; json["Birthday"]. Remove (0 ); JSON. Remove ("id"). Remove ("school" ); cout << "JSON =" << json << Endl; return 0 ;}/* Output:-----------------------id:18293 Name: "Ggicci" birthday-year:1991 birthday-month:11 Birth Day-day:10 man:true-----------------------json = {"Birthday": [1991, one, Ten], "id": 18293, "man": True, "name": "Mi Ngjie Tang "," School ":" Northwest A&f University "," Traits ": [" sympathetic "," Independent "]}---------------------- -JSON = {"Birthday": [One, ten], "Man": True, "name": "Mingjie Tang", "Traits": ["sympathetic", "Independent"]} */ If you're familiar with JSON processing (you might use JS to process JSON data), you'll find that the code above is well understood.
Comparison with JS usage (grammatical level)

For the original JSON string str: {"id": +, "name": "Ggicci", "Birthday": [1991, One, Ten]}

Js:var str = ‘{ "id": 1000, "name": "ggicci", "birthday": [1991, 11, 10] }‘;

C++:const char* str = "{\"id\": 1000, \"name\": \"ggicci\", \"birthday\": [1991, 11, 10] }";

Comparison of Json usage in Ggicci::json and JS
Function The JSON parser for JS Ggicci::json (assuming namespace Ggicci is declared below)
Parse and get JSON object var json = JSON.parse(str); Json json = Json::Parse(str);
Get number var id = json["id"]; int id = json["id"];
Get string var name = json["name"]; const char* name = json["name"];
string name = json["name"];
Get array var birthday = json["birthday"]; Json birthday = json["birthday"]; // 拷贝
Json &birthday = json["birthday"]; // 引用
Json *birthday = json["birthday"]; // 指针
Get NULL in Ggicci::json (required through JSON object, IsNull () function to determine whether the received data is null) Get object (need to get true,false via JSON object) (via bool value)
Modify number json["id"] = 19214; json["id"] = 19214;
Modify String json["name"] = "Mingjie Tang"; json["name"] = "Mingjie Tang";
Modify Array json["birthday"][2] = 11; json["birthday"][2] = 11;
Add Data (Array) json["birthday"].push(2013);
json["birthday"].push("hello");
json["birthday"].Push(2013).Push("hello");
Add Data (Object) json["man"] = true; json["man"] = true;
json.AddProperty("man", true);
Delete data (Array) Use Pop, unshift ... json["birthday"].Remove(0); // 不能级联
Delete data (Object) delete json["name"]; json.Remove("name").Remove("id"); // 可以级联
Get all keys for object // 复杂 vector<string> keys = json.Keys();

Exception HandlingParsing Exceptionsint main (int argc, Char const *Argv[]) {try{JSON JSON = JSON::P arse ("[1, 2, 2, {\" id\ ": 183, \" name\ ": ' Ggicci '}]"); } catch (exception&e) {cout << e.what () << Endl;//syntaxerror:unexpected token ' at POS 31} return 0; Use JS JSON under Chrome::p arse () function to parse the thrown exception:Data Acquisition Exceptionint main (int argc, Char const *Argv[]) {try{JSON JSON = JSON::P arse ("[1, 2, 3, 4]"); int first = json[0]; No problem const char* second = json[1]; Cause exception} catch (exception&e) {cout << e.what () << Endl;//Operationerror:illegal extract opeartion from number to String} return 0; }Illegal Operation exception[CPP] View plain copyint main (int argc, Char const *Argv[]) {try{JSON JSON = JSON::P arse ("[1, 2, 3, 4]"); Json. AddProperty ("name", "Ggicci"); Cause exception} catch (exception&e) {cout << e.what () << Endl;//Operationerror:illegal Add property opeartion on Array} return 0; }Type Detection[CPP] View plain copyint main (int argc, Char const * argv[]) {JSON JSON = JSON::P arse ("[1, \" Hello\ ", {\" title\ ": null}, False]" ), JSON. IsArray (); True json[0]. Isnumber (); True json[1]. Isstring (); True json[2]. IsObject (); True json[2]["title"]. IsNull (); True json[3]. Isbool (); True if  (JSON. IsArray ()) {for (int i = 0; i < JSON. Size (); + +  i) {switch  (Json[i]. Datakind ()) {case Json::knumber:cout << "number:"; Break , Case json::kstring:cout << "string:"; Break , Case json::karray:cout << "array:"; Break , Case json::kobject:cout << "object:"; Break , Case json::kbool:cout << "bool:"; Break , Case json::knull:cout << "null:"; Break ; default:break ;} cout << json[i] <<  Endl;} return 0 ;}/* output:number:1 String: "Hello" object: {"title": null} bool:false */         

A JSON parsing and processing library written in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.