MCPcopy Index your code
hub / github.com/DaveGamble/cJSON

github.com/DaveGamble/cJSON @v1.7.19

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.7.19 ↗ · + Follow
1,165 symbols 2,687 edges 117 files 143 documented · 12% 2 cross-repo links
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

cJSON

Ultralightweight JSON parser in ANSI C.

Table of contents

License

MIT License

Copyright (c) 2009-2017 Dave Gamble and cJSON contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Usage

Welcome to cJSON.

cJSON aims to be the dumbest possible parser that you can get your job done with. It's a single file of C, and a single header file.

JSON is described best here: http://www.json.org/ It's like XML, but fat-free. You use it to move data around, store things, or just generally represent your program's state.

As a library, cJSON exists to take away as much legwork as it can, but not get in your way. As a point of pragmatism (i.e. ignoring the truth), I'm going to say that you can use it in one of two modes: Auto and Manual. Let's have a quick run-through.

I lifted some JSON from this page: http://www.json.org/fatfree.html That page inspired me to write cJSON, which is a parser that tries to share the same philosophy as JSON itself. Simple, dumb, out of the way.

Building

There are several ways to incorporate cJSON into your project.

copying the source

Because the entire library is only one C file and one header file, you can just copy cJSON.h and cJSON.c to your projects source and start using it.

cJSON is written in ANSI C (C89) in order to support as many platforms and compilers as possible.

CMake

With CMake, cJSON supports a full blown build system. This way you get the most features. CMake with an equal or higher version than 2.8.5 is supported. With CMake it is recommended to do an out of tree build, meaning the compiled files are put in a directory separate from the source files. So in order to build cJSON with CMake on a Unix platform, make a build directory and run CMake inside it.

mkdir build
cd build
cmake ..

This will create a Makefile and a bunch of other files. You can then compile it:

make

And install it with make install if you want. By default it installs the headers /usr/local/include/cjson and the libraries to /usr/local/lib. It also installs files for pkg-config to make it easier to detect and use an existing installation of CMake. And it installs CMake config files, that can be used by other CMake based projects to discover the library.

You can change the build process with a list of different options that you can pass to CMake. Turn them on with On and off with Off:

  • -DENABLE_CJSON_TEST=On: Enable building the tests. (on by default)
  • -DENABLE_CJSON_UTILS=On: Enable building cJSON_Utils. (off by default)
  • -DENABLE_TARGET_EXPORT=On: Enable the export of CMake targets. Turn off if it makes problems. (on by default)
  • -DENABLE_CUSTOM_COMPILER_FLAGS=On: Enable custom compiler flags (currently for Clang, GCC and MSVC). Turn off if it makes problems. (on by default)
  • -DENABLE_VALGRIND=On: Run tests with valgrind. (off by default)
  • -DENABLE_SANITIZERS=On: Compile cJSON with AddressSanitizer and UndefinedBehaviorSanitizer enabled (if possible). (off by default)
  • -DENABLE_SAFE_STACK: Enable the SafeStack instrumentation pass. Currently only works with the Clang compiler. (off by default)
  • -DBUILD_SHARED_LIBS=On: Build the shared libraries. (on by default)
  • -DBUILD_SHARED_AND_STATIC_LIBS=On: Build both shared and static libraries. (off by default)
  • -DCMAKE_INSTALL_PREFIX=/usr: Set a prefix for the installation.
  • -DENABLE_LOCALES=On: Enable the usage of localeconv method. ( on by default )
  • -DCJSON_OVERRIDE_BUILD_SHARED_LIBS=On: Enable overriding the value of BUILD_SHARED_LIBS with -DCJSON_BUILD_SHARED_LIBS.
  • -DENABLE_CJSON_VERSION_SO: Enable cJSON so version. ( on by default )

If you are packaging cJSON for a distribution of Linux, you would probably take these steps for example:

mkdir build
cd build
cmake .. -DENABLE_CJSON_UTILS=On -DENABLE_CJSON_TEST=Off -DCMAKE_INSTALL_PREFIX=/usr
make
make DESTDIR=$pkgdir install

On Windows CMake is usually used to create a Visual Studio solution file by running it inside the Developer Command Prompt for Visual Studio, for exact steps follow the official documentation from CMake and Microsoft and use the online search engine of your choice. The descriptions of the the options above still generally apply, although not all of them work on Windows.

Makefile

NOTE: This Method is deprecated. Use CMake if at all possible. Makefile support is limited to fixing bugs.

If you don't have CMake available, but still have GNU make. You can use the makefile to build cJSON:

Run this command in the directory with the source code and it will automatically compile static and shared libraries and a little test program (not the full test suite).

make all

If you want, you can install the compiled library to your system using make install. By default it will install the headers in /usr/local/include/cjson and the libraries in /usr/local/lib. But you can change this behavior by setting the PREFIX and DESTDIR variables: make PREFIX=/usr DESTDIR=temp install. And uninstall them with: make PREFIX=/usr DESTDIR=temp uninstall.

Meson

To make cjson work in a project using meson, the libcjson dependency has to be included:

project('c-json-example', 'c')

cjson = dependency('libcjson')

example = executable(
    'example',
    'example.c',
    dependencies: [cjson],
)

Vcpkg

You can download and install cJSON using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install cjson

The cJSON port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Including cJSON

If you installed it via CMake or the Makefile, you can include cJSON like this:

#include <cjson/cJSON.h>

Data Structure

cJSON represents JSON data using the cJSON struct data type:

/* The cJSON structure: */
typedef struct cJSON
{
    struct cJSON *next;
    struct cJSON *prev;
    struct cJSON *child;
    int type;
    char *valuestring;
    /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
    int valueint;
    double valuedouble;
    char *string;
} cJSON;

An item of this type represents a JSON value. The type is stored in type as a bit-flag (this means that you cannot find out the type by just comparing the value of type).

To check the type of an item, use the corresponding cJSON_Is... function. It does a NULL check followed by a type check and returns a boolean value if the item is of this type.

The type can be one of the following:

  • cJSON_Invalid (check with cJSON_IsInvalid): Represents an invalid item that doesn't contain any value. You automatically have this type if you set the item to all zero bytes.
  • cJSON_False (check with cJSON_IsFalse): Represents a false boolean value. You can also check for boolean values in general with cJSON_IsBool.
  • cJSON_True (check with cJSON_IsTrue): Represents a true boolean value. You can also check for boolean values in general with cJSON_IsBool.
  • cJSON_NULL (check with cJSON_IsNull): Represents a null value.
  • cJSON_Number (check with cJSON_IsNumber): Represents a number value. The value is stored as a double in valuedouble and also in valueint. If the number is outside of the range of an integer, INT_MAX or INT_MIN are used for valueint.
  • cJSON_String (check with cJSON_IsString): Represents a string value. It is stored in the form of a zero terminated string in valuestring.
  • cJSON_Array (check with cJSON_IsArray): Represent an array value. This is implemented by pointing child to a linked list of cJSON items that represent the values in the array. The elements are linked together using next and prev, where the first element has prev.next == NULL and the last element next == NULL.
  • cJSON_Object (check with cJSON_IsObject): Represents an object value. Objects are stored same way as an array, the only difference is that the items in the object store their keys in string.
  • cJSON_Raw (check with cJSON_IsRaw): Represents any kind of JSON that is stored as a zero terminated array of characters in valuestring. This can be used, for example, to avoid printing the same static JSON over and over again to save performance. cJSON will never create this type when parsing. Also note that cJSON doesn't check if it is valid JSON.

Additionally there are the following two flags:

  • cJSON_IsReference: Specifies that the item that child points to and/or valuestring is not owned by this item, it is only a reference. So cJSON_Delete and other functions will only deallocate this item, not its child/valuestring.
  • cJSON_StringIsConst: This means that string points to a constant string. This means that cJSON_Delete and other functions will not try to deallocate string.

Working with the data structure

For every value type there is a cJSON_Create... function that can be used to create an item of that type. All of these will allocate a cJSON struct that can later be deleted with cJSON_Delete. Note that you have to delete them at some point, otherwise you will get a memory leak.
Important: If you have added an item to an array or an object already, you mustn't delete it with cJSON_Delete. Adding it to an array or object transfers its ownership so that when that array or object is deleted, it gets deleted as well. You also could use cJSON_SetValuestring to change a cJSON_String's valuestring, and you needn't to free the previous valuestring manually.

Basic types

  • null is created with cJSON_CreateNull
  • booleans are created with cJSON_CreateTrue, cJSON_CreateFalse or cJSON_CreateBool
  • numbers are created with cJSON_CreateNumber. This will set both valuedouble and valueint. If the number is outside of the range of an integer, INT_MAX or INT_MIN are used for valueint
  • strings are created with cJSON_CreateString (copies the string) or with cJSON_CreateStringReference (directly points to the string. This means that valuestring won't be deleted by cJSON_Delete and you are responsible for its lifetime, useful for constants)

Arrays

You can create an empty array with cJSON_CreateArray. cJSON_CreateArrayReference can be used to create an array that doesn't "own" its content, so its content doesn't get deleted by cJSON_Delete.

To add items to an array, use cJSON_AddItemToArray to append items to the end. Using cJSON_AddItemReferenceToArray an element can be added as a reference to another item, array or string. This means that cJSON_Delete will not delete that items child or valuestring properties, so no double frees are occurring if they are already used elsewhere. To insert items in the middle, use cJSON_InsertItemInArray. It will insert an item at the given 0 based index and shift all the existing items to the right.

If you want to take an item out of an array at a given index and continue using it, use cJSON_DetachItemFromArray, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak.

Deleting items is done with cJSON_DeleteItemFromArray. It works like cJSON_DetachItemFromArray, but deletes the detached item via cJSON_Delete.

You can also replace an item in an array in place. Either with cJSON_ReplaceItemInArray using an index or with `cJSON_

Core symbols most depended-on inside this repo

cJSON_Delete
called by 142
cJSON.c
UnityPrint
called by 86
tests/unity/src/unity.c
cJSON_CreateObject
called by 50
cJSON.c
reset
called by 35
tests/common.h
cJSON_GetObjectItemCaseSensitive
called by 34
cJSON.c
cJSON_Parse
called by 30
cJSON.c
cJSON_GetObjectItem
called by 30
cJSON.c
cJSON_AddItemToObject
called by 30
cJSON.c

Shape

Function 1,009
Method 126
Class 28
Enum 2

Languages

C85%
Ruby12%
C++1%
Python1%

Modules by API surface

tests/unity/test/tests/testunity.c368 symbols
cJSON.c118 symbols
tests/unity/src/unity.c45 symbols
cJSON_Utils.c39 symbols
tests/cjson_add.c33 symbols
tests/misc_tests.c32 symbols
tests/unity/test/testdata/testRunnerGeneratorWithMocks.c27 symbols
tests/unity/test/testdata/testRunnerGenerator.c26 symbols
tests/unity/extras/fixture/src/unity_fixture.c26 symbols
tests/unity/test/rakefile_helper.rb20 symbols
tests/unity/examples/example_3/rakefile_helper.rb20 symbols
tests/unity/auto/stylize_as_junit.rb18 symbols

Used by 2 indexed graphs manifest dependencies, hub-wide

For agents

$ claude mcp add cJSON \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact