DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • On Some Aspects of Big Data Processing in Apache Spark, Part 4: Versatile JSON and YAML Parsers
  • Building With Open Policy Agent (OPA) for Better Policy as Code
  • Building a Reddit Scraper in Go: JSON Listings, Pagination, Rate Limits, and Where It Breaks
  • Member Spotlight: Shai Almong

Trending

  • How an AI Software Factory Works: From Developer Intent to Production
  • GenAI Security Gateway: An End-to-End Architecture
  • One Database, Two Models: Building AI-Friendly Java Applications With MySQL JSON Duality Views
  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Simple and Easy-To-Use JSON Parser in C

Simple and Easy-To-Use JSON Parser in C

Explore the JSON parser of the open-source C library, Melon, and compare its features with the well-known cJSON. Understand the differences and similarities.

By 
Niklaus Schen
·
Oct. 26, 23 · Presentation
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
4.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

This article introduces the JSON parser of the open-source C library Melon.

I believe many readers have heard of or even used the cJSON. It is a very famous open-source project. In this article, we will compare cJSON and Melon’s JSON component.

Let’s take a look together below.

Encode

Suppose we want to build the following JSON:

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


So, let’s take a look at the cJSON version at first:

JSON
 
#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;
}


Next, let’s take a look at the Melon’s:

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;
}


The latter code is very short, and you can intuitively see the JSON format that will be generated.

Decode

We have the following JSON:

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

 


Let's take a look at the decoding, cJSON first:

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

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;
}


Next is the Melon's:

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

static int handler(mln_json_t *j, void *data)
{
    return (int)mln_json_number_data_get(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;
}


This time, there is not much difference in the number of lines between the two pieces of code. But in the latter implementation, a red-black tree is used as the storage data structure of the object type. Therefore, when facing objects with many keys, the search efficiency will be very stable.

Write at the End

Melon's JSON component mainly provides the following four functions to facilitate users to encode and decode JSON:

  • mln_json_decode decodes JSON strings into JSON structure nodes
  • mln_json_parse obtains the corresponding JSON sub-node from the decoded JSON structure based on the given expression
  • mln_json_generate builds a JSON structure based on the given format information
  • mln_json_encode generates a JSON string based on the generated JSON structure

Based on these four functions, JSON can be easily encoded and decoded, making it easier for developers to use and code maintenance.

Thanks for reading.

JSON Open source Parser (programming language)

Published at DZone with permission of Niklaus Schen. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • On Some Aspects of Big Data Processing in Apache Spark, Part 4: Versatile JSON and YAML Parsers
  • Building With Open Policy Agent (OPA) for Better Policy as Code
  • Building a Reddit Scraper in Go: JSON Listings, Pagination, Rate Limits, and Where It Breaks
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook