C json library windows

C-JSON

A lightweight and efficient JSON parsing library for C applications.


Overview

C-JSON is a minimal yet robust JSON parsing library designed for developers who need fast and efficient JSON handling in C. Whether you’re building embedded systems, working on performance-critical applications, or integrating JSON into your C projects, C-JSON provides the tools you need with minimal overhead.

With features like handling deeply nested structures, simple API integration, and comprehensive error handling, C-JSON ensures a smooth experience while processing JSON data efficiently.


Features

  • Lightweight and Fast: Built for performance and low memory usage.
  • Comprehensive Parsing:
    • JSON Objects
    • Arrays
    • Strings
    • Numbers (integers and floating-point)
    • Booleans
    • Null values
  • Supports Nested Structures: Handles deeply nested objects and arrays effortlessly.
  • Intuitive API: Easy-to-use functions for seamless integration.
  • Error Handling: Identifies and reports malformed JSON with helpful messages.
  • Cross-Platform: Compatible with Linux, macOS, and Windows.

Quick Start

Installation

  1. Clone the Repository
    Get the source code from GitHub:

    git clone https://github.com/OrcaLinux/c-json.git
    cd c-json
  2. Build the Library
    Compile the library using the provided Makefile:

  3. Run Tests
    Verify that the library is functioning as expected:


Integration

  1. Include the header file in your source code:

  2. Link the library during compilation:

    gcc -o my_program my_program.c -Lpath/to/json-parser/build -ljsonparser

Usage

Example: Parsing a Simple JSON Object

#include "json_parser.h"
#include <stdio.h>

int main() {
    const char* json_str = "{ \"name\": \"C-JSON\", \"version\": 1.0, \"active\": true }";

    JsonValue* root = json_parse(json_str);
    if (!root) {
        printf("Failed to parse JSON.\n");
        return 1;
    }

    // Access object values
    JsonValue* name = json_object_get(root, "name");
    JsonValue* version = json_object_get(root, "version");
    JsonValue* active = json_object_get(root, "active");

    if (name && name->type == JSON_STRING)
        printf("Name: %s\n", name->value.string);
    if (version && version->type == JSON_NUMBER)
        printf("Version: %.1f\n", version->value.number);
    if (active && active->type == JSON_BOOL)
        printf("Active: %s\n", active->value.boolean ? "true" : "false");

    json_free_value(root);
    return 0;
}

Example: Handling Nested Structures

#include "json_parser.h"
#include <stdio.h>

int main() {
    const char* json_str = "{ \"user\": { \"name\": \"Alice\", \"age\": 25 }, \"hobbies\": [\"reading\", \"swimming\"] }";

    JsonValue* root = json_parse(json_str);
    if (!root) {
        printf("Failed to parse JSON.\n");
        return 1;
    }

    // Access nested objects
    JsonValue* user = json_object_get(root, "user");
    if (user && user->type == JSON_OBJECT) {
        JsonValue* name = json_object_get(user, "name");
        JsonValue* age = json_object_get(user, "age");

        if (name && name->type == JSON_STRING)
            printf("Name: %s\n", name->value.string);
        if (age && age->type == JSON_NUMBER)
            printf("Age: %.0f\n", age->value.number);
    }

    // Access arrays
    JsonValue* hobbies = json_object_get(root, "hobbies");
    if (hobbies && hobbies->type == JSON_ARRAY) {
        printf("Hobbies:\n");
        for (size_t i = 0; i < hobbies->value.array->count; i++) {
            JsonValue* hobby = hobbies->value.array->items[i];
            if (hobby && hobby->type == JSON_STRING)
                printf("- %s\n", hobby->value.string);
        }
    }

    json_free_value(root);
    return 0;
}

Directory Structure

.
├── examples/
│   └── example_usage.c      # Example application showcasing library usage
├── include/
│   ├── json_accessor.h      # JSON accessor API header
│   ├── json_config.h        # Configuration file for JSON settings, e.g., debug flags
│   ├── json_logging.h       # Header for logging-related macros or functions
│   ├── json_parser.h        # Main parser API header
│   ├── json_printer.h       # JSON pretty-printing API header
│   ├── json_tokenizer.h     # Tokenizer API header
│   ├── json_types.h         # JSON type definitions
│   └── json_utils.h         # Utility functions header (memory management, etc.)
├── LICENSE                  # Project license
├── Makefile                 # Build instructions
├── README.md                # Project documentation
├── src/
│   ├── json_accessor.c      # Implementation of accessor functions
│   ├── json_config.c        # Implementation for configuration (not needed till now)
│   ├── json_logging.c       # Implementation for logging functionality (not needed till now)
│   ├── json_parser.c        # Implementation of the JSON parser
│   ├── json_printer.c       # Implementation of the JSON printer
│   ├── json_tokenizer.c     # Implementation of the tokenizer
│   └── json_utils.c         # Implementation of utility functions
└── tests/
    ├── test_parser.c        # Unit tests for the JSON parser
    └── test_tokenizer.c     # Unit tests for the tokenizer

Contributing

Contributions are welcome! To contribute:

  1. Fork the repository.
  2. Create a feature branch:
    git checkout -b feature/AmazingFeature
  3. Commit your changes:
    git commit -m "Add AmazingFeature"
  4. Push your branch:
    git push origin feature/AmazingFeature
  5. Open a pull request.

Roadmap

  • Add JSON serialization support.
  • Optimize parsing for large JSON files.
  • Add detailed error reporting.
  • Include performance benchmarks.

License

This project is licensed under the MIT License. See the LICENSE file for details.


Acknowledgments

  • Inspired by the simplicity and versatility of JSON.
  • Thanks to all contributors and open-source advocates.

  1. Overview and Build Status
  2. Getting Help
  3. Building on Unix
    • Prerequisites
    • Build commands
  4. CMake options
  5. Testing
  6. Building with `vcpkg`
  7. Building for Android
  1. Linking to libjson-c
  2. Using json-c

JSON-C — A JSON implementation in C

JSON-C implements a reference counting object model that allows you to easily construct JSON objects in C, output them as JSON formatted strings and parse JSON formatted strings back into the C representation of JSON objects. It aims to conform to RFC 8259.

Skip down to Using json-c or check out the API docs, if you already have json-c installed and ready to use.

Home page for json-c: https://github.com/json-c/json-c/wiki

Getting Help

If you have questions about using json-c, please start a thread on our forums at: https://groups.google.com/forum/#!forum/json-c

If you believe you’ve discovered a bug, report it at (https://github.com/json-c/json-c/issues). Please be sure to include the version of json-c you’re using, the OS you’re running on, and any other relevant details. Fully reproducible test cases and/or patches to fix problems are greatly appreciated.

Fixes for bugs, or small new features can be directly submitted as a pull request. For major new features or large changes of any kind, please first start a discussion on the forums.

Building on Unix with <tt>git</tt>, <tt>gcc</tt> and <tt>cmake</tt>

If you already have json-c installed, see Linking to `libjson-c` for how to build and link your program against it.

Build Status

Test Status

  • Coveralls

Prerequisites:

  • gcc, clang, or another C compiler
  • cmake>=2.8, >=3.16 recommended, cmake=>3.1 for tests

To generate docs you’ll also need:

  • doxygen>=1.8.13

If you are on a relatively modern system, you’ll likely be able to install the prerequisites using your OS’s packaging system.

Install using apt (e.g. Ubuntu 16.04.2 LTS)

sudo apt install git
sudo apt install cmake
sudo apt install doxygen  # optional
sudo apt install valgrind # optional

Build instructions:

json-c GitHub repo: https://github.com/json-c/json-c

$ git clone https://github.com/json-c/json-c.git
$ mkdir json-c-build
$ cd json-c-build
$ cmake ../json-c   # See CMake section below for custom arguments

Note: it’s also possible to put your build directory inside the json-c source directory, or even not use a separate build directory at all, but certain things might not work quite right (notably, make distcheck)

Then:

$ make
$ make test
$ make USE_VALGRIND=0 test   # optionally skip using valgrind
$ sudo make install          # it could be necessary to execute make install

Generating documentation with Doxygen:

The library documentation can be generated directly from the source code using Doxygen tool:

# in build directory
make doc
google-chrome doc/html/index.html

CMake Options

The json-c library is built with CMake, which can take a few options.

Variable Type Description
CMAKE_INSTALL_PREFIX String The install location.
CMAKE_BUILD_TYPE String Defaults to «debug».
BUILD_SHARED_LIBS Bool The default build generates a dynamic (dll/so) library. Set this to OFF to create a static library only.
BUILD_STATIC_LIBS Bool The default build generates a static (lib/a) library. Set this to OFF to create a shared library only.
DISABLE_STATIC_FPIC Bool The default builds position independent code. Set this to OFF to create a shared library only.
DISABLE_BSYMBOLIC Bool Disable use of -Bsymbolic-functions.
DISABLE_THREAD_LOCAL_STORAGE Bool Disable use of Thread-Local Storage (HAVE___THREAD).
DISABLE_WERROR Bool Disable use of -Werror.
DISABLE_EXTRA_LIBS Bool Disable use of extra libraries, libbsd
DISABLE_JSON_POINTER Bool Omit json_pointer support from the build.
ENABLE_RDRAND Bool Enable RDRAND Hardware RNG Hash Seed.
ENABLE_THREADING Bool Enable partial threading support.
OVERRIDE_GET_RANDOM_SEED String A block of code to use instead of the default implementation of json_c_get_random_seed(), e.g. on embedded platforms where not even the fallback to time() works. Must be a single line.

Pass these options as -D on CMake’s command-line.

# build a static library only
cmake -DBUILD_SHARED_LIBS=OFF ..

Building with partial threading support

Although json-c does not support fully multi-threaded access to object trees, it has some code to help make its use in threaded programs a bit safer. Currently, this is limited to using atomic operations for json_object_get() and json_object_put().

Since this may have a performance impact, of at least 3x slower according to https://stackoverflow.com/a/11609063, it is disabled by default. You may turn it on by adjusting your cmake command with: -DENABLE_THREADING=ON

Separately, the default hash function used for object field keys, lh_char_hash, uses a compare-and-swap operation to ensure the random seed is only generated once. Because this is a one-time operation, it is always compiled in when the compare-and-swap operation is available.

cmake-configure wrapper script

For those familiar with the old autoconf/autogen.sh/configure method, there is a cmake-configure wrapper script to ease the transition to cmake.

mkdir build
cd build
../cmake-configure --prefix=/some/install/path
make

cmake-configure can take a few options.

options Description
prefix=PREFIX install architecture-independent files in PREFIX
enable-threading Enable code to support partly multi-threaded use
enable-rdrand Enable RDRAND Hardware RNG Hash Seed generation on supported x86/x64 platforms.
enable-shared build shared libraries [default=yes]
enable-static build static libraries [default=yes]
disable-Bsymbolic Avoid linking with -Bsymbolic-function
disable-werror Avoid treating compiler warnings as fatal errors

Testing:

By default, if valgrind is available running tests uses it. That can slow the tests down considerably, so to disable it use:

export USE_VALGRIND=0

To run tests a separate build directory is recommended:

mkdir build-test
cd build-test
# VALGRIND=1 causes -DVALGRIND=1 to be passed when compiling code
# which uses slightly slower, but valgrind-safe code.
VALGRIND=1 cmake ..
make

make test
# By default, if valgrind is available running tests uses it.
make USE_VALGRIND=0 test   # optionally skip using valgrind

If a test fails, check Testing/Temporary/LastTest.log, tests/testSubDir/${testname}/${testname}.vg.out, and other similar files. If there is insufficient output try:

VERBOSE=1 CTEST_OUTPUT_ON_FAILURE=1 make test

or

JSONC_TEST_TRACE=1 make test

and check the log files again.

Building on Unix and Windows with <tt>vcpkg</tt>

You can download and install JSON-C using the vcpkg dependency manager:

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

The JSON-C 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.

Building for Android

Building on Android is now particularly well supported, but there have been some reports of success using https://developer.android.com/ndk/guides/cmake

mkdir json-c-build
cd json-c-build/
export NDK_HOME=~/Library/Android/sdk/ndk/22.1.7171670/
cmake \
    --toolchain=$NDK_HOME/build/cmake/android.toolchain.cmake \
    -DANDROID_STL=none \
    -DANDROID_ABI=arm64-v8a \
    -DANDROID_PLATFORM=android-29 \
    -DANDROID_LD=lld \
    -DCMAKE_BUILD_TYPE=MinSizeRel \
    -DCMAKE_INSTALL_PREFIX=<install prefix> \
    -DENABLE_THREADING=true \
    ..
make install

Linking to <tt>libjson-c</tt>

If your system has pkgconfig, then you can just add this to your makefile:

CFLAGS += $(shell pkg-config --cflags json-c)
LDFLAGS += $(shell pkg-config --libs json-c)

Without pkgconfig, you might do something like this:

JSON_C_DIR=/path/to/json_c/install
CFLAGS += -I$(JSON_C_DIR)/include/json-c
# Or to use lines like: #include <json-c/json_object.h>
#CFLAGS += -I$(JSON_C_DIR)/include
LDFLAGS+= -L$(JSON_C_DIR)/lib -ljson-c

If your project uses cmake:

  • Add to your CMakeLists.txt file:
find_package(json-c CONFIG)
target_link_libraries(${PROJECT_NAME} PRIVATE json-c::json-c)
  • Then you might run in your project:
cd build
cmake -DCMAKE_PREFIX_PATH=/path/to/json_c/install/lib64/cmake ..

Using json-c

To use json-c you can either include json.h, or preferably, one of the following more specific header files:

  • json_object.h — Core types and methods.
  • json_tokener.h — Methods for parsing and serializing json-c object trees.
  • json_pointer.h — JSON Pointer (RFC 6901) implementation for retrieving objects from a json-c object tree.
  • json_object_iterator.h — Methods for iterating over single json_object instances. (See also json_object_object_foreach() in json_object.h)
  • json_visit.h — Methods for walking a tree of json-c objects.
  • json_util.h — Miscellaneous utility functions.

For a full list of headers see files.html

The primary type in json-c is json_object. It describes a reference counted tree of json objects which are created by either parsing text with a json_tokener (i.e. json_tokener_parse_ex()), or by creating (with json_object_new_object(), json_object_new_int(), etc…) and adding (with json_object_object_add(), json_object_array_add(), etc…) them individually. Typically, every object in the tree will have one reference, from its parent. When you are done with the tree of objects, you call json_object_put() on just the root object to free it, which recurses down through any child objects calling json_object_put() on each one of those in turn.

You can get a reference to a single child (json_object_object_get() or json_object_array_get_idx()) and use that object as long as its parent is valid.
If you need a child object to live longer than its parent, you can increment the child’s refcount (json_object_get()) to allow it to survive the parent being freed or it being removed from its parent (json_object_object_del() or json_object_array_del_idx())

When parsing text, the json_tokener object is independent from the json_object that it returns. It can be allocated (json_tokener_new()) used one or multiple times (json_tokener_parse_ex(), and freed (json_tokener_free()) while the json_object objects live on.

A json_object tree can be serialized back into a string with json_object_to_json_string_ext(). The string that is returned is only valid until the next «to_json_string» call on that same object. Also, it is freed when the json_object is freed.

Last Updated :
24 Apr, 2025

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language.

JSON in C

JSON in C can be handled using the cJSON library, which is an open-source library available under the MIT License. It provides a simple and easy-to-use API for parsing, creating, and manipulating JSON data. The cJSON library is written in C and has no external dependencies, making it easy to integrate into C programs.

Writing JSON Data

To write JSON data in C, we need to create a cJSON object and convert it to a JSON string using the cJSON library. Here is an example code snippet to write JSON data to a file:

C

#include <stdio.h>

#include <cjson/cJSON.h>

int main() {

   cJSON *json = cJSON_CreateObject();

   cJSON_AddStringToObject(json, "name", "John Doe");

   cJSON_AddNumberToObject(json, "age", 30);

   cJSON_AddStringToObject(json, "email", "john.doe@example.com");

   char *json_str = cJSON_Print(json);

   FILE *fp = fopen("data.json", "w");

   if (fp == NULL) {

       printf("Error: Unable to open the file.\n");

       return 1;

   }

   printf("%s\n", json_str);

   fputs(json_str, fp);

   fclose

   cJSON_free(json_str);

   cJSON_Delete(json);

   return 0;

}

Output: 

Console Output

{
    "name": "John Doe",
    "age": 30,
    "email": "john.doe@example.com"
}

Generated JSON file

Generated JSON file

Generated JSON file

Code Explanation:

In this example, we first create a cJSON object using the `cJSON_CreateObject()` function. We then add key-value pairs to the object using the `cJSON_AddStringToObject()` and `cJSON_AddNumberToObject()` functions. We then convert the cJSON object to a JSON string using the `cJSON_Print()` function, which returns a dynamically allocated string that needs to be freed using the `cJSON_free()` function. We then write the JSON string to a file using the `fputs()` function. Finally, we delete the cJSON object using the `cJSON_Delete()` function.

Note 1: In the above program, the output is the JSON data written to a file named “data.json”. The contents of the file are the same as the JSON data printed to the console.

Note 2: The formatting of the JSON data in the output may differ depending on the operating system and text editor used. However, the contents of the JSON data will remain the same.

Reading JSON Data

To read JSON data in C, we need to parse the JSON string using the cJSON library. Here is an example code snippet to read JSON data from a file:

C

#include <stdio.h>

#include <cjson/cJSON.h>

int main() {

    FILE *fp = fopen("data.json", "r");

    if (fp == NULL) {

        printf("Error: Unable to open the file.\n");

        return 1;

    }

    char buffer[1024];

    int len = fread(buffer, 1, sizeof(buffer), fp);

    fclose(fp);

    cJSON *json = cJSON_Parse(buffer);

    if (json == NULL) {

        const char *error_ptr = cJSON_GetErrorPtr();

        if (error_ptr != NULL) {

            printf("Error: %s\n", error_ptr);

        }

        cJSON_Delete(json);

        return 1;

    }

    cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name");

    if (cJSON_IsString(name) && (name->valuestring != NULL)) {

        printf("Name: %s\n", name->valuestring);

    }

    cJSON_Delete(json);

    return 0;

}

Input: (JSON File)

JSON File for input

JSON File for input

Output: 

Name: John Doe

In this example, we first open the JSON file using the fopen() function and check if it is successful. Then we read the file contents into a buffer using the fread() function. We close the file using the fclose() function. We then parse the JSON data using the cJSON_Parse() function, which returns a pointer to a cJSON object. If the parsing fails, we print the error message using the cJSON_GetErrorPtr() function. We then access the JSON data using the cJSON_GetObjectItemCaseSensitive() function, which returns a pointer to a cJSON object corresponding to the given key. Finally, we delete the cJSON object using the cJSON_Delete() function.

Modifying Existing JSON file Data

Certainly! To modify an existing JSON file, we can use the cJSON library’s functions to read the file into a cJSON object, modify the object, and then write the modified object back to the file. Here’s an example program that demonstrates how to modify a JSON file using the cJSON library in C:

C

#include <stdio.h>

#include <cjson/cJSON.h>

int main() {

    FILE *fp = fopen("data.json", "r");

    if (fp == NULL) {

        printf("Error: Unable to open the file.\n");

        return 1;

    }

    char buffer[1024];

    int len = fread(buffer, 1, sizeof(buffer), fp);

    fclose(fp);

    cJSON *json = cJSON_Parse(buffer);

    if (json == NULL) {

        const char *error_ptr = cJSON_GetErrorPtr();

        if (error_ptr != NULL) {

            printf("Error: %s\n", error_ptr);

        }

        cJSON_Delete(json);

        return 1;

    }

    cJSON_ReplaceItemInObjectCaseSensitive(json, "name", cJSON_CreateString("Jane Doe"));

    cJSON_AddNumberToObject(json, "age", 32);

    cJSON_AddStringToObject(json, "phone", "555-555-5555");

    char *json_str = cJSON_Print(json);

    fp = fopen("data.json", "w");

    if (fp == NULL) {

        printf("Error: Unable to open the file.\n");

        return 1;

    }

    printf("%s\n", json_str);

    fputs(json_str, fp);

    fclose(fp);

    cJSON_free(json_str);

    cJSON_Delete(json);

    return 0;

}

In this example program, we first open the JSON file, read its contents into a string, and parse the JSON data using the cJSON_Parse() function. We then modify the JSON data by replacing the value of the “name” key with a new string, adding a new key-value pair for “phone”, and changing the value of the “age” key to 32. We then convert the cJSON object back to a JSON string using the cJSON_Print() function, write the JSON string to the file using the fputs() function, and free the cJSON object and JSON string. After running this program, the “data.json” file should now contain the modified JSON data.

Input: (JSON File)

JSON file for input

JSON file for input

Output:

Console

{
   "name": "Jane Doe",
   "age": 32,
   "email": "john.doe@example.com",
   "phone": "555-555-5555"
}

Modified JSON File

Modified JSON file

Modified JSON file

Note: In this example, we used the cJSON_ReplaceItemInObjectCaseSensitive() function to replace the value of the “name” key, which is case-sensitive. If the key is not case-sensitive, we can use the cJSON_ReplaceItemInObject() function instead. Also, we can modify the JSON data in any way we want using the cJSON library’s various functions.

Conclusion

In this article, we discussed how to read and write JSON data in C using the cJSON library. The cJSON library provides a simple and easy-to-use API for handling JSON data in C. By using this library, we can easily integrate JSON data into our C programs and exchange data with other applications and web services.

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Введение в JSON и его использование

JSON (JavaScript Object Notation) — это легковесный формат обмена данными, который легко читается и пишется человеком, а также легко парсится и генерируется машинами. JSON используется для передачи данных между сервером и веб-приложением, а также для хранения данных в файлах. Основные преимущества JSON включают его простоту, гибкость и широкую поддержку в различных языках программирования. JSON стал стандартом де-факто для передачи данных в веб-приложениях благодаря своей легкости и универсальности. Он поддерживает различные типы данных, такие как строки, числа, массивы, объекты и логические значения, что делает его очень гибким и мощным инструментом для обмена данными.

Кинга Идем в IT: пошаговый план для смены профессии

Парсинг JSON на C: библиотеки и примеры

Для парсинга JSON на языке C существует несколько популярных библиотек, таких как cJSON, Jansson и json-c. Рассмотрим использование библиотеки cJSON, которая является одной из самых популярных и простых в использовании. Эти библиотеки предоставляют удобные функции для работы с JSON-данными, такие как парсинг, генерация и манипуляция JSON-объектами. Они также обеспечивают высокую производительность и гибкость, что делает их отличным выбором для различных приложений.

Установка cJSON

Для начала необходимо установить библиотеку cJSON. Это можно сделать с помощью пакетного менеджера или вручную, скачав исходный код с GitHub. Установка через пакетный менеджер обычно проще и быстрее, так как он автоматически решает все зависимости и устанавливает необходимые файлы. Установка вручную требует больше усилий, но дает больше контроля над процессом и позволяет настроить библиотеку под конкретные нужды.

Пример парсинга JSON с использованием cJSON

Рассмотрим пример парсинга простого JSON-объекта:

Пример кода на C:

Этот пример демонстрирует, как парсить JSON-строку и извлекать значения полей. В данном коде мы используем функции cJSON для парсинга строки JSON и извлечения значений полей. Функция cJSON_Parse преобразует строку JSON в объект cJSON, который можно использовать для доступа к данным. Функции cJSON_GetObjectItemCaseSensitive и cJSON_IsString позволяют извлекать значения полей и проверять их типы.

Парсинг JSON на Python: библиотеки и примеры

Python имеет встроенную поддержку JSON через модуль json, что делает его использование очень простым и удобным. Этот модуль предоставляет функции для парсинга JSON-строк и генерации JSON-данных из Python-объектов. Он также поддерживает различные опции для настройки процесса парсинга и генерации, что делает его очень гибким и мощным инструментом для работы с JSON.

Пример парсинга JSON с использованием модуля json

Рассмотрим тот же JSON-объект и пример кода на Python:

Этот код показывает, как легко можно парсить JSON-строку и извлекать значения полей в Python. В данном примере мы используем функцию json.loads для преобразования строки JSON в Python-объект. Затем мы можем легко получить доступ к значениям полей с помощью стандартных операторов доступа к элементам словаря. Это делает работу с JSON в Python очень простой и интуитивно понятной.

Парсинг JSON на JavaScript: библиотеки и примеры

JavaScript также имеет встроенную поддержку JSON через объекты JSON.parse и JSON.stringify. Эти функции позволяют легко парсить JSON-строки и генерировать JSON-данные из JavaScript-объектов. Они также поддерживают различные опции для настройки процесса парсинга и генерации, что делает их очень гибкими и мощными инструментами для работы с JSON.

Пример парсинга JSON с использованием JSON.parse

Рассмотрим тот же JSON-объект и пример кода на JavaScript:

Этот пример демонстрирует, как легко можно парсить JSON-строку и извлекать значения полей в JavaScript. В данном коде мы используем функцию JSON.parse для преобразования строки JSON в JavaScript-объект. Затем мы можем легко получить доступ к значениям полей с помощью стандартных операторов доступа к свойствам объекта. Это делает работу с JSON в JavaScript очень простой и интуитивно понятной.

Сравнение производительности и удобства использования

Производительность

Производительность парсинга JSON может варьироваться в зависимости от языка программирования и используемой библиотеки. В общем, C будет быстрее, чем Python и JavaScript, из-за своей низкоуровневой природы и отсутствия интерпретации. Однако, это также делает код на C более сложным и менее удобным для написания и отладки. Производительность парсинга JSON в C может быть критически важной для приложений, требующих высокой скорости обработки данных, таких как системы реального времени и высокопроизводительные серверы.

Удобство использования

Python и JavaScript предлагают более высокоуровневые и удобные для использования библиотеки для работы с JSON, что делает их предпочтительными для большинства разработчиков. В Python и JavaScript парсинг JSON выполняется с минимальными усилиями, что позволяет сосредоточиться на логике приложения, а не на деталях реализации. Удобство использования этих языков делает их отличным выбором для быстрого прототипирования и разработки приложений, где важна скорость разработки и простота кода.

Заключение

Каждый язык программирования имеет свои сильные и слабые стороны при работе с JSON. C предлагает высокую производительность, но требует больше усилий для написания и отладки кода. Python и JavaScript предлагают простоту и удобство использования, что делает их отличным выбором для большинства задач, связанных с JSON. В зависимости от конкретных требований вашего проекта, вы можете выбрать наиболее подходящий язык и библиотеку для работы с JSON. Если вам нужна высокая производительность и контроль над процессом, C может быть лучшим выбором. Если важна простота и скорость разработки, Python и JavaScript будут более подходящими вариантами.

Читайте также

Release date: 

Saturday, 29 December, 2012

License:

  • Open source (generic)

Interface:

  • PMShell
  • Workplace Shell
  • VIO
  • Italiano

Alan Coopersmith, Alexander Dahl, Alexandru Ardelean, andy5995, Aram Poghosyan, Björn Esser, BonsaY, changyong guo, chenguoping, Chris Lamb, Christopher Head, Chris Wolfe, C. Watford, Darjan Krijan, David McCann, DeX77, dota17, Haszlakiewicz, Eric Hawicz, Even Rouault, Gianluigi Tiesi, grdowns, Hex052, hofnarr, ihsinme, Ivan Romanov, Jaap Keuter, Jakov Smolic, janczer, Jehan, Jehiah Czebotar, Jonathan Wiens, José Bollo, Juuso Alasuutari, Keith Holman, Kizuna-Meraki, Leon Gross, Liang Gao, Marc, max, Micah Snyder, Michael Clark, myd7349, Pascal Cuoq, Pawday, Philosoph228, Pierce Lopez, Po-Chuan Hsieh, Ramiro Polla, Rikard Falkeborn, Robert Bielik, Robert, Rosen Penev, Rubasri Kalidas, Simon McVittie, ssrlive, Tobias Nießen, Tobias Stoeckmann, Tudor Brindus, Unmanned Player, Netlabs

Json-c library provides a C language implementation for JSON (JavaScript Object Notation) data format-interchange client/server. JSON is a lightweight data-interchange format based on a subset of the JavaScript Programming Language, well know for web developing.

This software is distributed as RPM package.

Installation with rpm

Repository: Netlabs stable

  • install with ANPM or running the command:
    yum install json-c
  • manually download as ZIP file package:
    http://rpm.netlabs.org/release/00/zip/json-c-0_16-1_oc00.zip

0.16 (up to commit 66dcdf5, 2022-04-13)
========================================

Deprecated and removed features:
———————————
* JSON_C_OBJECT_KEY_IS_CONSTANT is deprecated in favor of
JSON_C_OBJECT_ADD_CONSTANT_KEY
* Direct access to lh_table and lh_entry structure members is deprecated.
Use access functions instead, lh_table_head(), lh_entry_next(), etc…
* Drop REFCOUNT_DEBUG code.

New features
————
* The 0.16 release introduces no new features

Build changes
————-
* Add a DISABLE_EXTRA_LIBS option to skip using libbsd
* Add a DISABLE_JSON_POINTER option to skip compiling in json_pointer support.

Significant changes and bug fixes
———————————
* Cap string length at INT_MAX to avoid various issues with very long strings.
* json_object_deep_copy: fix deep copy of strings containing ‘\0’
* Fix read past end of buffer in the «json_parse» command
* Avoid out of memory accesses in the locally provided vasprintf() function
(for those platforms that use it)
* Handle allocation failure in json_tokener_new_ex
* Fix use-after-free in json_tokener_new_ex() in the event of printbuf_new() returning NULL
* printbuf_memset(): set gaps to zero — areas within the print buffer which
have not been initialized by using printbuf_memset
* printbuf: return -1 on invalid arguments (len < 0 or total buffer > INT_MAX)
* sprintbuf(): propagate printbuf_memappend errors back to the caller

Optimizations
—————
* Speed up parsing by replacing ctype functions with simplified, faster
non-locale-sensitive ones in json_tokener and json_object_to_json_string.
* Neither vertical tab nor formfeed are considered whitespace per the JSON spec
* json_object: speed up creation of objects, calloc() -> malloc() + set fields
* Avoid needless extra strlen() call in json_c_shallow_copy_default() and
json_object_equal() when the object is known to be a json_type_string.

Other changes
————-
* Validate size arguments in arraylist functions.
* Use getrandom() if available; with GRND_NONBLOCK to allow use of json-c
very early during boot, such as part of cryptsetup.
* Use arc4random() if it’s available.
* random_seed: on error, continue to next method instead of exiting the process
* Close file when unable to read from /dev/urandom in get_dev_random_seed()

***

Repository: Netlabs stable
(note: development files, not needed by the end user)

  • install with ANPM or running the command:
    yum install json-c-devel

Record updated last time on: 15/02/2023 — 21:59

Translate to…

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Обновить аудио кодеки для windows 10
  • Smartmontools windows как пользоваться
  • System windows forms nugget
  • Создание нескольких учетных записей в windows 10
  • Настройка заметок в windows