当前位置:网站首页>JSON Library Tutorial from scratch (I): starting to learn and organize notes

JSON Library Tutorial from scratch (I): starting to learn and organize notes

2022-06-25 05:17:00 zhongh58

Original website : From scratch JSON Library Tutorial - You know

 JSON What is it? ?

JSON(JavaScript Object Notation) Is a text format for data exchange .

JSON It's a tree structure , Contains only 6 Type of data :

  • null: Expressed as null
  • boolean: Expressed as true or false
  • number: General representation of floating point numbers , Explain in detail in the next module
  • string: Expressed as "..."
  • array: Expressed as [ ... ]
  • object: Expressed as { ... }

What we want to achieve JSON library , Mainly completed 3 A need :

  1. hold JSON The text is parsed into a tree data structure (parse).
  2. Provide an interface to access the data structure (access).
  3. Convert the data structure into JSON Text (stringify).

JSON There is 6 Type of data , If you put true and false As two types, they are 7 Kind of , We declare an enumeration type for this (enumeration type):

typedef enum {   
                 LEPT_NULL, 
                 LEPT_FALSE, 
                 LEPT_TRUE, 
                 LEPT_NUMBER,
                 LEPT_STRING, 
                 LEPT_ARRAY, 
                 LEPT_OBJECT 
             } lept_type;

JSON It's a tree structure , We finally need to implement a tree data structure , Each node uses lept_value The structure represents , We'll call it a JSON value (JSON value).

typedef struct {
    lept_type type;
}lept_value;

We only need two now API function , One is parsing JSON:

int lept_parse(lept_value* v, const char* json);

The return values are the following enumerated values , No error will be returned LEPT_PARSE_OK.

enum {
    LEPT_PARSE_OK = 0,
    LEPT_PARSE_EXPECT_VALUE,
    LEPT_PARSE_INVALID_VALUE,
    LEPT_PARSE_ROOT_NOT_SINGULAR
};
  • If one JSON Contains only white space , Send back LEPT_PARSE_EXPECT_VALUE.
  • If after a value , There are other characters after whitespace , Send back LEPT_PARSE_ROOT_NOT_SINGULAR.
  • If the value is not the three literal values , Send back LEPT_PARSE_INVALID_VALUE.

Now we only need a function to access the result , Is to get its type :

lept_type lept_get_type(const lept_value* v);

To reduce the number of arguments passed between analytic functions , We put json Put all the data into one lept_context Structure :

typedef struct {
    const char* json;
}lept_context;

原网站

版权声明
本文为[zhongh58]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210518428436.html