Convert Figma logo to code with AI

zserge logojsmn

Jsmn is a world fastest JSON parser/tokenizer. This is the official repo replacing the old one at Bitbucket

3,648
777
3,648
97

Top Related Projects

Ultra-lightweight JavaScript engine for the Internet of Things.

1,850

Embedded JavaScript engine for C/C++

5,921

Duktape - embeddable Javascript engine with a focus on portability and compact footprint

8,251

Public repository of the QuickJS Javascript Engine.

Quick Overview

JSMN (pronounced like "jasmine") is a minimalistic JSON parser in C. It is designed to be simple, portable, and fast, with a focus on parsing JSON data without creating an object model or using dynamic memory allocation.

Pros

  • Extremely lightweight and fast
  • No dynamic memory allocation, suitable for embedded systems
  • Easy to integrate into existing projects
  • Supports streaming JSON parsing

Cons

  • Limited functionality compared to full-featured JSON libraries
  • Requires manual handling of parsed tokens
  • No built-in JSON generation capabilities
  • May require more code to use effectively compared to higher-level libraries

Code Examples

Parsing a simple JSON string:

#include "jsmn.h"

const char *JSON_STRING = "{\"name\":\"John\",\"age\":30}";
jsmn_parser p;
jsmntok_t t[10]; // We expect no more than 10 tokens

jsmn_init(&p);
int r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0]));

// r > 0 means successful parsing

Accessing parsed tokens:

if (r > 1 && t[1].type == JSMN_STRING) {
    // Access the "name" value
    int name_length = t[2].end - t[2].start;
    char name[20];
    strncpy(name, JSON_STRING + t[2].start, name_length);
    name[name_length] = '\0';
    printf("Name: %s\n", name);
}

Parsing a JSON array:

const char *JSON_ARRAY = "[1,2,3,4,5]";
jsmn_parser p;
jsmntok_t t[10];

jsmn_init(&p);
int r = jsmn_parse(&p, JSON_ARRAY, strlen(JSON_ARRAY), t, sizeof(t)/sizeof(t[0]));

for (int i = 1; i < r; i++) {
    if (t[i].type == JSMN_PRIMITIVE) {
        printf("Array element: %.*s\n", t[i].end - t[i].start, JSON_ARRAY + t[i].start);
    }
}

Getting Started

  1. Download jsmn.h and jsmn.c from the GitHub repository.
  2. Include the files in your project.
  3. Include the header in your C file:
#include "jsmn.h"
  1. Initialize a parser and parse JSON:
jsmn_parser p;
jsmntok_t t[MAX_TOKENS];
const char *JSON = "{\"key\":\"value\"}";

jsmn_init(&p);
int r = jsmn_parse(&p, JSON, strlen(JSON), t, sizeof(t)/sizeof(t[0]));

if (r < 0) {
    printf("Failed to parse JSON\n");
} else {
    // Process tokens
}
  1. Compile your project, linking jsmn.c with your source files.

Competitor Comparisons

Ultra-lightweight JavaScript engine for the Internet of Things.

Pros of JerryScript

  • Full-featured JavaScript engine, supporting ECMAScript 5.1 with some ES2015+ features
  • Designed for resource-constrained devices, making it suitable for IoT and embedded systems
  • Extensive documentation and active community support

Cons of JerryScript

  • Larger codebase and more complex implementation compared to JSMN
  • Higher memory footprint and resource requirements
  • Steeper learning curve for integration and customization

Code Comparison

JSMN (JSON parsing):

jsmn_parser p;
jsmntok_t t[128];
jsmn_init(&p);
int r = jsmn_parse(&p, json_string, strlen(json_string), t, sizeof(t)/sizeof(t[0]));

JerryScript (JavaScript execution):

jerry_init(JERRY_INIT_EMPTY);
jerry_value_t eval_ret = jerry_eval((jerry_char_t *) script, script_size, JERRY_PARSE_NO_OPTS);
jerry_release_value(eval_ret);
jerry_cleanup();

Summary

JSMN is a minimalist JSON parser, while JerryScript is a full JavaScript engine. JSMN is lightweight and focused on JSON parsing, making it ideal for simple JSON-related tasks. JerryScript offers a complete JavaScript runtime environment, suitable for more complex applications requiring JavaScript execution in resource-constrained environments. The choice between them depends on the specific requirements of the project, with JSMN being simpler to integrate for JSON parsing, and JerryScript providing more extensive JavaScript capabilities at the cost of increased complexity and resource usage.

1,850

Embedded JavaScript engine for C/C++

Pros of mjs

  • Full JavaScript engine with support for ES6 features
  • Ability to execute JavaScript code dynamically
  • Integrated with Mongoose OS for IoT development

Cons of mjs

  • Larger footprint and resource usage
  • More complex implementation and maintenance
  • Potentially slower parsing and execution for simple JSON tasks

Code Comparison

mjs (JavaScript execution):

char *js_code = "print('Hello, World!');";
struct mjs *mjs = mjs_create();
mjs_exec(mjs, js_code, NULL);
mjs_destroy(mjs);

jsmn (JSON parsing):

jsmn_parser p;
jsmntok_t t[128];
jsmn_init(&p);
int r = jsmn_parse(&p, json_string, strlen(json_string), t, sizeof(t)/sizeof(t[0]));

Summary

mjs is a full JavaScript engine suitable for embedded systems and IoT devices, offering dynamic code execution and ES6 features. jsmn, on the other hand, is a minimalistic JSON parser focused on efficiency and small footprint. While mjs provides more functionality, it comes at the cost of increased complexity and resource usage. jsmn is better suited for simple JSON parsing tasks in resource-constrained environments.

5,921

Duktape - embeddable Javascript engine with a focus on portability and compact footprint

Pros of Duktape

  • Full-featured JavaScript engine with ECMAScript E5/E5.1 compliance
  • Supports embedding in C/C++ projects for running JavaScript
  • Includes a debugger and built-in regular expression engine

Cons of Duktape

  • Larger footprint and more complex than JSMN
  • May be overkill for simple JSON parsing tasks
  • Steeper learning curve for basic usage

Code Comparison

JSMN (simple JSON parsing):

jsmn_parser p;
jsmntok_t t[128];
jsmn_init(&p);
int r = jsmn_parse(&p, json_string, strlen(json_string), t, sizeof(t)/sizeof(t[0]));

Duktape (JavaScript execution):

duk_context *ctx = duk_create_heap_default();
duk_push_string(ctx, "print('Hello, world!');");
duk_eval(ctx);
duk_destroy_heap(ctx);

Summary

JSMN is a lightweight JSON parser focused on simplicity and small footprint, while Duktape is a full-fledged JavaScript engine with more features but increased complexity. Choose JSMN for simple JSON parsing tasks and Duktape for projects requiring JavaScript execution or more advanced JSON manipulation.

8,251

Public repository of the QuickJS Javascript Engine.

Pros of QuickJS

  • Full-featured JavaScript engine with ECMAScript 2020 support
  • Includes a standalone interpreter and compiler
  • Lightweight and embeddable in C programs

Cons of QuickJS

  • Larger codebase and more complex implementation
  • Higher memory footprint compared to JSMN
  • Potentially slower for simple parsing tasks

Code Comparison

JSMN (parsing JSON):

jsmn_parser p;
jsmntok_t t[128];
jsmn_init(&p);
int r = jsmn_parse(&p, json_string, strlen(json_string), t, sizeof(t)/sizeof(t[0]));

QuickJS (executing JavaScript):

JSRuntime *rt = JS_NewRuntime();
JSContext *ctx = JS_NewContext(rt);
JSValue result = JS_Eval(ctx, script, strlen(script), "<input>", JS_EVAL_TYPE_GLOBAL);

Summary

JSMN is a minimalist JSON parser in C, while QuickJS is a full JavaScript engine. JSMN is simpler and more lightweight, ideal for embedded systems or when only JSON parsing is needed. QuickJS offers a complete JavaScript environment, suitable for applications requiring full ECMAScript compatibility and execution capabilities.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

JSMN

Build Status

jsmn (pronounced like 'jasmine') is a minimalistic JSON parser in C. It can be easily integrated into resource-limited or embedded projects.

You can find more information about JSON format at json.org

Library sources are available at https://github.com/zserge/jsmn

The web page with some information about jsmn can be found at http://zserge.com/jsmn.html

Philosophy

Most JSON parsers offer you a bunch of functions to load JSON data, parse it and extract any value by its name. jsmn proves that checking the correctness of every JSON packet or allocating temporary objects to store parsed JSON fields often is an overkill.

JSON format itself is extremely simple, so why should we complicate it?

jsmn is designed to be robust (it should work fine even with erroneous data), fast (it should parse data on the fly), portable (no superfluous dependencies or non-standard C extensions). And of course, simplicity is a key feature - simple code style, simple algorithm, simple integration into other projects.

Features

  • compatible with C89
  • no dependencies (even libc!)
  • highly portable (tested on x86/amd64, ARM, AVR)
  • about 200 lines of code
  • extremely small code footprint
  • API contains only 2 functions
  • no dynamic memory allocation
  • incremental single-pass parsing
  • library code is covered with unit-tests

Design

The rudimentary jsmn object is a token. Let's consider a JSON string:

'{ "name" : "Jack", "age" : 27 }'

It holds the following tokens:

  • Object: { "name" : "Jack", "age" : 27} (the whole object)
  • Strings: "name", "Jack", "age" (keys and some values)
  • Number: 27

In jsmn, tokens do not hold any data, but point to token boundaries in JSON string instead. In the example above jsmn will create tokens like: Object [0..31], String [3..7], String [12..16], String [20..23], Number [27..29].

Every jsmn token has a type, which indicates the type of corresponding JSON token. jsmn supports the following token types:

  • Object - a container of key-value pairs, e.g.: { "foo":"bar", "x":0.3 }
  • Array - a sequence of values, e.g.: [ 1, 2, 3 ]
  • String - a quoted sequence of chars, e.g.: "foo"
  • Primitive - a number, a boolean (true, false) or null

Besides start/end positions, jsmn tokens for complex types (like arrays or objects) also contain a number of child items, so you can easily follow object hierarchy.

This approach provides enough information for parsing any JSON data and makes it possible to use zero-copy techniques.

Usage

Download jsmn.h, include it, done.

#include "jsmn.h"

...
jsmn_parser p;
jsmntok_t t[128]; /* We expect no more than 128 JSON tokens */

jsmn_init(&p);
r = jsmn_parse(&p, s, strlen(s), t, 128); // "s" is the char array holding the json content

Since jsmn is a single-header, header-only library, for more complex use cases you might need to define additional macros. #define JSMN_STATIC hides all jsmn API symbols by making them static. Also, if you want to include jsmn.h from multiple C files, to avoid duplication of symbols you may define JSMN_HEADER macro.

/* In every .c file that uses jsmn include only declarations: */
#define JSMN_HEADER
#include "jsmn.h"

/* Additionally, create one jsmn.c file for jsmn implementation: */
#include "jsmn.h"

API

Token types are described by jsmntype_t:

typedef enum {
	JSMN_UNDEFINED = 0,
	JSMN_OBJECT = 1 << 0,
	JSMN_ARRAY = 1 << 1,
	JSMN_STRING = 1 << 2,
	JSMN_PRIMITIVE = 1 << 3
} jsmntype_t;

Note: Unlike JSON data types, primitive tokens are not divided into numbers, booleans and null, because one can easily tell the type using the first character:

  • 't', 'f' - boolean
  • 'n' - null
  • '-', '0'..'9' - number

Token is an object of jsmntok_t type:

typedef struct {
	jsmntype_t type; // Token type
	int start;       // Token start position
	int end;         // Token end position
	int size;        // Number of child (nested) tokens
} jsmntok_t;

Note: string tokens point to the first character after the opening quote and the previous symbol before final quote. This was made to simplify string extraction from JSON data.

All job is done by jsmn_parser object. You can initialize a new parser using:

jsmn_parser parser;
jsmntok_t tokens[10];

jsmn_init(&parser);

// js - pointer to JSON string
// tokens - an array of tokens available
// 10 - number of tokens available
jsmn_parse(&parser, js, strlen(js), tokens, 10);

This will create a parser, and then it tries to parse up to 10 JSON tokens from the js string.

A non-negative return value of jsmn_parse is the number of tokens actually used by the parser. Passing NULL instead of the tokens array would not store parsing results, but instead the function will return the number of tokens needed to parse the given string. This can be useful if you don't know yet how many tokens to allocate.

If something goes wrong, you will get an error. Error will be one of these:

  • JSMN_ERROR_INVAL - bad token, JSON string is corrupted
  • JSMN_ERROR_NOMEM - not enough tokens, JSON string is too large
  • JSMN_ERROR_PART - JSON string is too short, expecting more JSON data

If you get JSMN_ERROR_NOMEM, you can re-allocate more tokens and call jsmn_parse once more. If you read json data from the stream, you can periodically call jsmn_parse and check if return value is JSMN_ERROR_PART. You will get this error until you reach the end of JSON data.

Other info

This software is distributed under MIT license, so feel free to integrate it in your commercial products.