# zjson **Repository Path**: grdu/zjson ## Basic Information - **Project Name**: zjson - **Description**: 从node.js转到c++,特别怀念在js中使用json那种畅快感。在c++中也使用过了些库,但提供的接口使用方式,总不是习惯,很烦锁,接口函数太多,不直观。参考了很多库,如:rapidjson, cJson, CJsonObject, drleq-cppjson, json11等,受cJson的数据结构启发很大,决定用C++手撸一个。 - **Primary Language**: C++ - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 8 - **Created**: 2025-03-14 - **Last Updated**: 2025-03-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ZJSON    [中文介绍](README_CN.md) ## Introduce From node.Js back to c++. I especially miss the pleasure of using json in javascript, so try to diy one. I used many libraries, such as: rapidjson, cJson, CJsonObject, drleq cppjson, json11, etc. Zjson's data structure is greatly inspired by cJOSN. The parsing part refers to json11, thanks! Finally, because data storage needs not only to distinguish values, but also to know their types. I choose std:: variant and std:: any which supported by C++17. Finally, the C++ version is fixed at C++17. This library is designed as a single header file, not relying on any other lib than the C++ standard library. ## Design ideas Simple interface functions, simple use methods, flexible data structures, and support chain operations as much as possible. Realizing the simplest design using template technology. Adding a child object of Json only needs one function -- addSubitem, which automatically identifies whether it is a value or a child Json object. The Json object is stored in a linked list structure (refers to cJSON). Please see my data structure design as follows. The header and the following nodes use the same structure, which enables chained operations during index operations ([]). ## Project progress At present, the project has completed most of functions. Please refer to the task list for details. task list: - [x] constructor(Object & Array) - [x] constructor(values) - [x] JSON serializable constructor - [x] copy constructor - [x] initializer_list constructor - [x] destructor - [x] operator= - [x] operator[] - [x] contains - [x] getValueType - [x] getAndRemove - [x] getAllKeys - [x] addSubitem(add subitems & add items to array rapidly) - [x] toString(generate josn string) - [x] toInt、toDouble、toFalse - [x] toVector - [x] isError、isNull、isArray - [x] parse - from Json string to Json object - [x] Extend - Json - [x] concat - Json - [x] push_front - Json - [x] push_back - Json - [x] insert - Json - [x] clear - [x] std::move - [x] Remove key - [x] Remove intger - [x] pop pop_back pop_front - [x] removeFirst removeLast remove(for array) - [x] slice - [x] takes take - [ ] performance test and comparison for recursive version - [ ] algorithm non recursion - [ ] performance test and comparison again ## Data structure ### Json node type > For internal use, the data type is only used inside the Json class ``` enum Type { Error, //error or a invalid Json False, //Json value type - false True, //Json value type - true Null, //Json value type - null Number, //Json value type - numerial String, //Json value type - string Object, //Json object type Array //Json object type }; ``` ### Json node define ``` class Json { Json* brother; //like cJSON's next Json* child; //chile node, for object type Type type; //node type std::variant data; //node's data string name; //node's key } ``` ## Interface Object type, only support Object and Array. ``` enum class JsonType { Object = 6, Array = 7 }; ``` Api list - Json(JsonType type = JsonType::Object)      //constructor default, can generate Object or Array - template<typename T> Json(T value, string key="")        //value constructor - Json(const Json& origin)              //move constructor - Json(Json&& rhs)              //copy constructor - Json(string jsonStr)               //deserialized constructor - explicit Json(std::initializer_list<std::pair<const std::string, Json>> values)     //initializer_list Object constructor - Json& operator = (const Json& origin)        - Json& operator = (Json&& origin)        - Json operator[](const int& index)         - Json operator[](const string& key)          - template<typename T> bool addSubitem(T value)       - template<typename T> bool addSubitem(string name, T value) //add a subitem - string toString()                  - bool isError()                  - bool isNull()                   - bool isObject()                  - bool isArray()                  - bool isNumber()                  - bool isTrue()                   - bool isFalse()                  - int toInt()                     - float toFloat()                   - double toDouble()                - bool toBool()                   - vector<Json> toVector()              - bool extend(Json value)             - bool concat(Json value)            //for array object - bool push_front(Json value)            //for array object - bool push_back(Json value)            //for array object - bool insert(int index, Json value)           //for array object - void clear()            //clear child - void remove(const string &key)           - bool contains(const string& key)             - string getValueType()           //return value's type in string - Json getAndRemove(const string& key)            - std::vector getAllKeys()            ## Examples ``` Json subObject{{"math", 99},{"str", "a string."}}; Json mulitListObj{{"fkey", false},{"strkey","ffffff"},{"num2", 9.98}, {"okey", subObject}}; Json subArray(JsonType::Array); subArray.add({12,13,14,15}); Json ajson(JsonType::Object); std::string data = "kevin"; ajson.add("fail", false); ajson.add("name", data); ajson.add("school-en", "the 85th."); ajson.add("age", 10); ajson.add("scores", 95.98); ajson.add("nullkey", nullptr); Json sub; sub.add("math", 99); ajson.addValueJson("subJson", sub); Json subArray(JsonType::Array); subArray.add("I'm the first one."); subArray.add("two", 2); Json sub2; sub2.add("sb2", 222); subArray.addValueJson("subObj", sub2); ajson.addValueJson("array", subArray); std::cout << "ajson's string is : " << ajson.toString() << std::endl; string name = ajson["name"].toString(); int oper = ajson["sb2"].toInt(); Json operArr = ajson["array"]; string first = ajson["array"][0].toString(); ``` result of mulitListObj: ``` { "fkey": false, "strkey": "ffffff", "num2": 9.98, "okey": { "math": 99, "str": "a string." } } ``` result of ajson: ``` { "fail": false, "name": "kevin", "school-en": "the 85th.", "age": 10, "scores": 95.98, "nullkey": null, "subJson": { "math": 99 }, "array": [ "I'm the first one.", 2, { "sb2": 222 } ] } ``` Detailed description, please move to demo.cpp or unit test in tests catalogue. ## Project site ``` https://gitee.com/zhoutk/zjson or https://github.com/zhoutk/zjson ``` ## run guidance The project is built in vs2019, gcc7.5, clang12.0 success. ``` git clone https://github.com/zhoutk/zjson cd zjson cmake -Bbuild . ---windows cd build && cmake --build . ---linux & mac cd build && make run zjson or ctest ``` ## Associated projects > [zorm](https://gitee.com/zhoutk/zorm.git) (General Encapsulation of Relational Database) ``` https://gitee.com/zhoutk/zorm or https://github.com/zhoutk/zorm ```