当前位置:网站首页>[JSON tutorial] Chapter 1 learning notes
[JSON tutorial] Chapter 1 learning notes
2022-06-30 06:49:00 【ypd.】

This work adopts Creative Commons signature - Noncommercial use - Share in the same way 4.0 International licensing agreement Licensing .
intro
This blog series is about learning json-tutorial project Some insights of
I feel that learning this project is very important for using
C LanguageIt is very helpful to develop something that is actually useful , And the author's teaching is very detailed , The code is also very standard , I decided to learnThis project is a zero start JSON Library Tutorial , The difficulty is suitable for those who have studied
basic C/C++ ProgrammingClassmateMy coding environment is
GNU/LinuxMint OS, Use gcc Compile codeThis blog is about json-tutorial The first chapter is the understanding and thinking of the content
The content mainly focuses on the double check notes of the places that were difficult to understand at that time , Instead of taking detailed notes of everything
turtorial01.md
What to achieve
When I first opened the tutorial , It's really a fog , Even if the author's tutorial is written in great detail , But there is still a feeling that there is no way to start , So about this project , What exactly do we want to achieve ?
About what to achieve JSON library , It needs to implement three requirements
- hold JSON The text is parsed as a
Treesdata structure –(parse) - Provide an interface to access the data structure –(
access) - Convert the data structure into JSON Text –(
stringify)
- hold JSON The text is parsed as a
The main objective has been determined , It's obviously complicated , But the goal of the first chapter is simple , You just need to implement the
nullAndbooleanCan be resolved
How to do that
- In order to achieve the right
null And booleanParsing , We need to :- stay
leptjson.hDefine the following requiredstructureAndFunction signature - stay
leptjson.cTo realizeParser - stay
test.cTo implement aunit testing
- stay
- It needs to be
codingThere are only three places , Two of the three documents implement the requirements , A guarantee that the requirements are normally implemented , The overall framework is not complicated
Difficult to understand
- Understand what the author has provided in Chapter one
macroIt is a little difficult point , This macro is very simple , But it's still hard to understand if you haven't been in touch with Changhong before , We mainly need to understand its nesting - You need to understand that if the program is
Assertion (assert)The crash is due to the programmer's code Existing problems
SHOW ME THE CODE
- The code here is the code after achieving the task goal
- The code is the core of this project , Let's annotate the code in detail !
- This project adopts C89, So the comments section can only use
/* something */
leptjson.h
#ifndef LEPTJSON_H__
#define LEPTJSON_H__
/* About JSON Enumeration values of data types */
typedef enum {
LEPT_NULL, LEPT_FALSE, LEPT_TRUE, LEPT_NUMBER, LEPT_STRING, LEPT_ARRAY, LEPT_OBJECT } lept_type;
/*JSON Data structure of , In the first chapter, we only need lept_type Type is enough */
typedef struct {
lept_type type;
}lept_value;
/* About the enumeration value of the return value */
enum {
LEPT_PARSE_OK = 0,
LEPT_PARSE_EXPECT_VALUE, /* Indicates that there is only white space */
LEPT_PARSE_INVALID_VALUE, /* There are other characters after whitespace */
LEPT_PARSE_ROOT_NOT_SINGULAR
};
/* analysis JSON Function of */
int lept_parse(lept_value* v, const char* json);
/* Access the return value result , Get its type function */
lept_type lept_get_type(const lept_value* v);
#endif /* LEPTJSON_H__ */
leptjson.c
- .c File length of , Let's look at it separately
Macros and structures
macro
#define EXPECT(c, ch) do {
assert(*c->json == (ch)); c->json++; } while(0)
This macro is very simple , To assert that the parameters passed in by the function are what we want , If you crash here , shows coding The wrong... Was called when API
Structure
typedef struct {
const char* json;
}lept_context;
- take JSON Information is put into a structure , The main purpose is to avoid passing multiple parameters between subsequent analytic functions
Parser
lept_parse
- Pass in the character you actually want to compare (
v) and Standard characters (json)
int lept_parse(lept_value* v, const char* json) {
/* v Is the character I actually want to compare , json Is a standard character for example lept_parse(&v, "null") */
/* Because to be right v Change the indicated string , So define a temporary variable c*/
lept_context c;
int ret;
/* Is not to say that v The string constant of cannot be null, It is v The space pointed to cannot be empty */
assert(v != NULL);
c.json = json;
/* if lept_parse() Failure , Will be able to v Set to null type So let's set it to null Give Way lept_parse_value() Write the resolved root value */
v->type = LEPT_NULL;
/* JSON-text = ws value ws Pass in c, The comparison uses c->json */
lept_parse_whitespace(&c);
if((ret = lept_parse_value(&c, v)) == LEPT_PARSE_OK){
lept_parse_whitespace(&c);
if(*c.json != '\0'){
ret = LEPT_PARSE_ROOT_NOT_SINGULAR;
}
}
/* return lept_parse_value(&c, v); */
return ret;
}
lept_parse_value
static int lept_parse_value(lept_context* c, lept_value* v) {
/* distinguish value after , Start matching */
switch (*c->json) {
case 'n': return lept_parse_null(c, v);
case 'f': return lept_parse_false(c, v);
case 't': return lept_parse_true(c, v);
case '\0': return LEPT_PARSE_EXPECT_VALUE;
default: return LEPT_PARSE_INVALID_VALUE;
}
}
lept_get_type
- as long as v Is a meaningful value , Just go back to v The type of
lept_type lept_get_type(const lept_value* v) {
assert(v != NULL);
/* v Of type stay lept_parse() Specified in the call */
return v->type;
}
Residual function
- The remaining functions are easy to understand , Are called separately to perform a single parsing task
test.c
- A simple test unit , It can provide test points to test whether our code can meet the target requirements
macro
- The macro of test unit is a small difficulty in Chapter 1 , In fact, we only need to understand
\stay C The role of the language and the relationship between the two macros can be well understood , And you can feel the convenience of macros ~~( Macro magic )~~
static int main_ret = 0;
static int test_count = 0;
static int test_pass = 0;
#define EXPECT_EQ_BASE(equality, expect, actual, format) \ do {
\ /* Each call means the number of test points plus one */ \ test_count++;\ if (equality)\ /* adopt */ \ test_pass++;\ else {
\ /* Because what is passed in is an enumeration value , So it is %d */ \ fprintf(stderr, "%s:%d: expect: " format " actual: " format "\n", __FILE__, __LINE__, expect, actual);\ main_ret = 1;\ }\ } while(0)
/* The program calls the second macro , Just enter two values , The second macro calls the first macro to complete the check */
#define EXPECT_EQ_INT(expect, actual) EXPECT_EQ_BASE((expect) == (actual), expect, actual, "%d")
test_parse()
/* Execute sequentially , One by one */
static void test_parse() {
test_parse_null();
test_parse_true();
test_parse_false();
test_parse_expect_value();
test_parse_invalid_value();
test_parse_root_not_singular();
}
demo
static int lept_parse_true(lept_context* c, lept_value* v) {
/* Match validation first character */
EXPECT(c, 't');
/* When verifying the first character, there is an offset of one character , So from [0] Start */
if (c->json[0] != 'r' || c->json[1] != 'u' || c->json[2] != 'e')
return LEPT_PARSE_INVALID_VALUE;
c->json += 3;
v->type = LEPT_TRUE;
return LEPT_PARSE_OK;
}
- The implementation of Chapter 1 ends here , Are some very basic content , But as expected, it is better to write it out
Reference resources
边栏推荐
- Rising posture series: fancy debugging information
- GO安装以及配置(1)
- 1.9 - Cache
- 1.2 (supplementary)
- 不忘初心,能偷懒就偷懒:C#操作Word文件
- 成品升级程序
- Improve simulation speed during ROS and Px4 joint simulation
- Pay attention to this live broadcast and learn about the path to achieve the dual carbon goal of the energy industry
- No module named 'pyqt5 QtMultimedia‘
- Control method of UAV formation
猜你喜欢
随机推荐
我开户后把账号忘记了咋办?股票在网上开户安全吗?
Ffmplay is not generated during the compilation and installation of ffmpeg source code
写一个C程序判断系统是大端字节序还是小端字节序
ini解析學習文檔
Spin official tutorial
Graphic octet, really top
Keil - the "trace HW not present" appears during download debugging
关注这场直播,了解能源行业双碳目标实现路径
原理:WebMvcConfigurer 与 WebMvcConfigurationSupport避坑指南
Connect to remote server
ftplib+ tqdm 上传下载进度条
Deep learning --- the weight of the three good students' scores (3)
Switch must be better than if Else fast
0基础转行软件测试,如何实现月薪9.5k+
Records of problems solved (continuously updated)
File transfer protocol, FTP file sharing server
1.7 - CPU performance indicators
【模糊神经网络】基于模糊神经网络的移动机器人路径规划
Wechat applet mall project
力扣------替换空格









