惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
Engineering at Meta
Engineering at Meta
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
量子位
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
L
LangChain Blog
A
About on SuperTechFans
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
美团技术团队
博客园 - 三生石上(FineUI控件)
N
Netflix TechBlog - Medium
D
DataBreaches.Net
P
Proofpoint News Feed
小众软件
小众软件
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss
WordPress大学
WordPress大学
雷峰网
雷峰网
G
Google Developers Blog

C

C 语言快速通关教程 2026(共 96 集) - V2EX 各位大佬, C 語言該怎麼練習啊 分享一个代码优化导致的死循环 人再笨还能写不出内存安全的 C? 想念 C C11 的 _Generic,现实当中用得多不多?(尤其是公司项目) 坑爹的 GBK:大家都应该去用 UTF-8 分享一个用 AI 学习 C 语言的例子 一个简单的 C 程序,但是不明白区别在哪里 我这段 C 代码可以在编译时候输出结构体的大小,你们还有什么好点子, show me the code! 这段话是否正确?「取余这个运算,只有 Python 是对的。当初 C 这个老师教错了,那么一大票学生也就只敢跟着老师错。只有 Python 敢于站出来坚持正确答案。」 C 中可变参数如何直接传递到 printf() C 的内存打印实现 函数能否实现透传不定长度参数,最终由 printf 打印 请大佬帮忙修改一份 elf 文件里的数值 Linux 上 C 的程序遇到个异常退出问题,局部变量大小有限制?? C 语言新手求助:如何在 vscode 中使用第三方库? 将资源嵌入到可执行文件中并保持目录结构 一个简单实用的 C 工程示例, 附简洁的 Makefile 关于 C 语言的相关问题 轮子更新: C/C++ 跨平台小工具库 为什么下列程序进行的是无符号乘法? 用 riscv64- Linux -gnu-gcc 编译的 c 文件为啥能在 x8664 下运行? char *s = "0123"和 char s[] = "0123"的区别 有人能完整地解释一下 int (*daytab) [13]和 int *daytab[13]吗 在 c 语言中, int a;是 declaration 还是 definition 一个简单(奇怪)的 C 语言问题 c 语言中打印指针的值打印的是 OS 分配的虚拟地址的值吗?要怎么知道 OS 给这个 c 程序进程分配的虚拟地址的大小呢? gcc 是怎么找到 system 函数的定义(实现)的? 用 C 实现轻量级表达式完成策略定制化和模板内容生成
最好用的 C 语言 JSON 解析器
monkeyNik · 2023-09-12 · via C

本文介绍开源 C 语言库Melon的 JSON 解析器。

相信很多读者都听说过甚至使用过 cJSON 开源库。那么本文就拿 cJSON 与 Melon 的 JSON 组件进行对比。

下面我们就来一起看一看。

编码 Encode

假设我们要构建如下 JSON:

{
    "name": "Awesome 4K",
    "resolutions": [
        {
            "width": 1280,
            "height": 720
        },
        {
            "width": 1920,
            "height": 1080
        },
        {
            "width": 3840,
            "height": 2160
        }
    ]
}

那么,我们先看一下cJSON的构建代码:

#include <stdio.h>
#include <cjson/cJSON.h>

//NOTE: Returns a heap allocated string, you are required to free it after use.
char *create_monitor_with_helpers(void)
{
    const unsigned int resolution_numbers[3][2] = {
        {1280, 720},
        {1920, 1080},
        {3840, 2160}
    };
    char *string = NULL;
    cJSON *resolutions = NULL;
    size_t index = 0;

    cJSON *monitor = cJSON_CreateObject();

    if (cJSON_AddStringToObject(monitor, "name", "Awesome 4K") == NULL)
    {
        goto end;
    }

    resolutions = cJSON_AddArrayToObject(monitor, "resolutions");
    if (resolutions == NULL)
    {
        goto end;
    }

    for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
    {
        cJSON *resolution = cJSON_CreateObject();

        if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL)
        {
            goto end;
        }

        if (cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL)
        {
            goto end;
        }

        cJSON_AddItemToArray(resolutions, resolution);
    }

    string = cJSON_Print(monitor);
    if (string == NULL)
    {
        fprintf(stderr, "Failed to print monitor.\n");
    }

end:
    cJSON_Delete(monitor);
    return string;
}

int main(void)
{
    char *p;
    p = create_monitor_with_helpers();
    printf("%s\n", p);
    return 0;
}

下面,我们一起看下使用Melon 的 JSON 组件的代码:

#include <stdio.h>
#include "mln_json.h"
#include "mln_log.h"

static mln_string_t *generate(void)
{
    mln_json_t j;
    mln_string_t *ret;

    mln_json_init(&j);

    mln_json_generate(&j, "{s:s,s:[{s:d,s:d},{s:d,s:d},{s:d,s:d}]}", \
        "name", "Awesome 4K", "resolutions", "width", 1280, "height", 720, \
        "width", 1920, "height", 1080, "width", 3840, "height", 2160);
    ret = mln_json_encode(&j);

    mln_json_destroy(&j);

    return ret;
}

int main(void)
{
    mln_string_t *p;
    p = generate();
    mln_log(none, "%S\n", p);
    return 0;
}

解码 Decode

假设我们有如下 JSON:

{
    "name": "Awesome 4K",
    "resolutions": [
        {
            "width": 1280,
            "height": 720
        }
    ]
}

下面一起来看下解码,还是先上cJSON的代码:

#include <stdio.h>
#include <cjson/cJSON.h>

/* return 1 if the monitor supports full hd, 0 otherwise */
int supports_full_hd(const char * const monitor)
{
    const cJSON *resolution = NULL;
    const cJSON *resolutions = NULL;
    cJSON *monitor_json = cJSON_Parse(monitor);
    if (monitor_json == NULL)
        return -1;

    resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions");
    cJSON_ArrayForEach(resolution, resolutions)
    {
        cJSON *width = cJSON_GetObjectItemCaseSensitive(resolution, "width");
        return width->valuedouble;
    }

    cJSON_Delete(monitor_json);
    return -1;
}

int main(void)
{
    char p[] = "{\"name\":\"Awesome 4K\",\"resolutions\":[{\"width\":1280,\"height\":720}]}";
    int i = supports_full_hd(p);
    printf("%d\n", i);
    return 0;
}

接下来是Melon 的 JSON 组件的解码代码:

#include <stdio.h>
#include "mln_json.h"
#include "mln_log.h"

static int handler(mln_json_t *j, void *data)
{
    return (int)M_JSON_GET_DATA_NUMBER(j);
}

static int parse(mln_string_t *p)
{
    mln_json_t j;
    mln_string_t exp = mln_string("resolutions.0.width");
    mln_json_decode(p, &j);
    return mln_json_parse(&j, &exp, handler, NULL);
}

int main(void)
{
    mln_string_t p = mln_string("{\"name\":\"Awesome 4K\",\"resolutions\":[{\"width\":1280,\"height\":720}]}");
    int i = parse(&p);
    mln_log(none, "%d\n", i);
    return 0;
}

结语

Melon 的 JSON 组件主要提供了如下四个函数来便于使用者构建和解析 JSON:

  • mln_json_decode解码 JSON 字符串为 JSON 结构体结点
  • mln_json_parse从解码的 JSON 结构体中,根据给定表达式,获取对应的 JSON 子结点
  • mln_json_generate根据给定的格式信息构建 JSON 结构体
  • mln_json_encode根据生成的 JSON 结构体生成 JSON 字符串

Melon 的 JSON 组件提供了易于阅读和使用的函数接口,更易于开发者对项目的维护。

欢迎大家来试用开源 C 语言库 Melon 。

Github: https://github.com/Water-Melon/Melon