kandi background
Explore Kits

cJSON | Ultralightweight JSON parser in ANSI C | Parser library

 by   DaveGamble C Version: v1.7.15 License: MIT

 by   DaveGamble C Version: v1.7.15 License: MIT

Download this library from

kandi X-RAY | cJSON Summary

cJSON is a C library typically used in Utilities, Parser, Nodejs applications. cJSON has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
Ultralightweight JSON parser in ANSI C.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • cJSON has a medium active ecosystem.
  • It has 6193 star(s) with 2280 fork(s). There are 269 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 64 open issues and 322 have been closed. On average issues are closed in 48 days. There are 31 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of cJSON is v1.7.15
cJSON Support
Best in #Parser
Average in #Parser
cJSON Support
Best in #Parser
Average in #Parser

quality kandi Quality

  • cJSON has 0 bugs and 0 code smells.
cJSON Quality
Best in #Parser
Average in #Parser
cJSON Quality
Best in #Parser
Average in #Parser

securitySecurity

  • cJSON has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • cJSON code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
cJSON Security
Best in #Parser
Average in #Parser
cJSON Security
Best in #Parser
Average in #Parser

license License

  • cJSON is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
cJSON License
Best in #Parser
Average in #Parser
cJSON License
Best in #Parser
Average in #Parser

buildReuse

  • cJSON releases are available to install and integrate.
  • Installation instructions are not available. Examples and code snippets are available.
  • It has 3309 lines of code, 140 functions and 18 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
cJSON Reuse
Best in #Parser
Average in #Parser
cJSON Reuse
Best in #Parser
Average in #Parser
Top functions reviewed by kandi - BETA

Coming Soon for all Libraries!

Currently covering the most popular Java, JavaScript and Python libraries. See a SAMPLE HERE.
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.

cJSON Key Features

Ultralightweight JSON parser in ANSI C

Building

copy iconCopydownload iconDownload
mkdir build
cd build
cmake ..

Including cJSON

copy iconCopydownload iconDownload
#include <cjson/cJSON.h>

Data Structure

copy iconCopydownload iconDownload
/* 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;

Parsing JSON

copy iconCopydownload iconDownload
cJSON *json = cJSON_Parse(string);

Printing JSON

copy iconCopydownload iconDownload
char *string = cJSON_Print(json);

Example

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

How can I convert an int (which represents an decimal without its decimal places) to a double in c?

copy iconCopydownload iconDownload
cJSON* addDecimalToJSON(cJSON* const object, const char * const name, 
                        const int number, const int decimals) {
    double d = number;
    for(int i = 0; i < decimals; i++) {
        d = d / 10;
    }
    char dstr[50];
    sprintf(dstr,"%.*f", decimals, d);
    return addStringToObject(object, name, dstr);
}

Send Json Payload to californium server

copy iconCopydownload iconDownload
cJSON_Init();
cJSON *item = createJsonFromParams();
char *payload=cJSON_Print(item);
coap_packet_append_payload(&request, (uint8_t *)payload, sizeof(payload)-1);
char payload[] = "I'm a array";

printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
char *payload=cJSON_Print(item);
printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
coap_packet_append_payload(&request, (uint8_t *)payload, strlen(payload));
-----------------------
cJSON_Init();
cJSON *item = createJsonFromParams();
char *payload=cJSON_Print(item);
coap_packet_append_payload(&request, (uint8_t *)payload, sizeof(payload)-1);
char payload[] = "I'm a array";

printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
char *payload=cJSON_Print(item);
printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
coap_packet_append_payload(&request, (uint8_t *)payload, strlen(payload));
-----------------------
cJSON_Init();
cJSON *item = createJsonFromParams();
char *payload=cJSON_Print(item);
coap_packet_append_payload(&request, (uint8_t *)payload, sizeof(payload)-1);
char payload[] = "I'm a array";

printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
char *payload=cJSON_Print(item);
printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
coap_packet_append_payload(&request, (uint8_t *)payload, strlen(payload));
-----------------------
cJSON_Init();
cJSON *item = createJsonFromParams();
char *payload=cJSON_Print(item);
coap_packet_append_payload(&request, (uint8_t *)payload, sizeof(payload)-1);
char payload[] = "I'm a array";

printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
char *payload=cJSON_Print(item);
printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
coap_packet_append_payload(&request, (uint8_t *)payload, strlen(payload));
-----------------------
cJSON_Init();
cJSON *item = createJsonFromParams();
char *payload=cJSON_Print(item);
coap_packet_append_payload(&request, (uint8_t *)payload, sizeof(payload)-1);
char payload[] = "I'm a array";

printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
char *payload=cJSON_Print(item);
printf("sizeof %d, strlen %d\n", sizeof(payload), strlen(payload));
coap_packet_append_payload(&request, (uint8_t *)payload, strlen(payload));

How to handle POST request with JSON payload on ESP32 server?

copy iconCopydownload iconDownload
<form action="javascript:void(0);">
  <input type="text" id="mytext1" />
  <button onclick="submitData()">Submit</button>
</form>

<script>
  async function submitData() {
    const mytext1 = document.getElementById("mytext1").value;

    const body = { mytext1 };

    const response = await fetch("target_page", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    });

    // if your server responds with text
    const serverResponse = await response.text();

    ...
  }
</script>

Parsing json array response / flutter

copy iconCopydownload iconDownload
part 'example.g.dart';

@JsonSerializable()
class Channel{
  final String id;
  final String name;
  final String? imageUrl;
  Channel({required this.id, required this.name, this.imageUrl});
  factory Channel.fromJson(Map<String, dynamic> json) => _$ChannelFromJson(json);
  Map<String, dynamic> toJson() => _$ChannelToJson(this);
}



@JsonSerializable()
class ChannelList{
  final List<Channel> myChannels;
  ChannelList({required this.myChannels});
  factory ChannelList.fromJson(Map<String, dynamic> json) => _$ChannelListFromJson(json);
  Map<String, dynamic> toJson() => _$ChannelListToJson(this);
}
-----------------------
class ApiResponse {
  ApiResponse({
    required this.myChannels,
  });

  List<MyChannel> myChannels;

  factory ApiResponse.fromJson(Map<String, dynamic> json) => ApiResponse(
        myChannels: List<MyChannel>.from(
          json["myChannels"].map((x) => MyChannel.fromJson(x)),
        ),
      );
}

class MyChannel {
  MyChannel({
    required this.id,
    required this.name,
    required this.imageUrl,
  });

  String id;
  String name;
  String imageUrl;

  factory MyChannel.fromJson(Map<String, dynamic> json) => MyChannel(
        id: json["id"],
        name: json["name"],
        imageUrl: json["imageUrl"],
      );
}
final extractedData = ApiResponse.fromJson(json.decode(response.body) as Map<String, dynamic>);
extractedData.myChannels[0].id
extractedData.myChannels[0].name
extractedData.myChannels[0].imageUrl

for (var ch in extractedData.myChannels){
 print(ch.id);
 print(ch.name);
 print(ch.imageUrl);
}
-----------------------
class ApiResponse {
  ApiResponse({
    required this.myChannels,
  });

  List<MyChannel> myChannels;

  factory ApiResponse.fromJson(Map<String, dynamic> json) => ApiResponse(
        myChannels: List<MyChannel>.from(
          json["myChannels"].map((x) => MyChannel.fromJson(x)),
        ),
      );
}

class MyChannel {
  MyChannel({
    required this.id,
    required this.name,
    required this.imageUrl,
  });

  String id;
  String name;
  String imageUrl;

  factory MyChannel.fromJson(Map<String, dynamic> json) => MyChannel(
        id: json["id"],
        name: json["name"],
        imageUrl: json["imageUrl"],
      );
}
final extractedData = ApiResponse.fromJson(json.decode(response.body) as Map<String, dynamic>);
extractedData.myChannels[0].id
extractedData.myChannels[0].name
extractedData.myChannels[0].imageUrl

for (var ch in extractedData.myChannels){
 print(ch.id);
 print(ch.name);
 print(ch.imageUrl);
}
-----------------------
class ApiResponse {
  ApiResponse({
    required this.myChannels,
  });

  List<MyChannel> myChannels;

  factory ApiResponse.fromJson(Map<String, dynamic> json) => ApiResponse(
        myChannels: List<MyChannel>.from(
          json["myChannels"].map((x) => MyChannel.fromJson(x)),
        ),
      );
}

class MyChannel {
  MyChannel({
    required this.id,
    required this.name,
    required this.imageUrl,
  });

  String id;
  String name;
  String imageUrl;

  factory MyChannel.fromJson(Map<String, dynamic> json) => MyChannel(
        id: json["id"],
        name: json["name"],
        imageUrl: json["imageUrl"],
      );
}
final extractedData = ApiResponse.fromJson(json.decode(response.body) as Map<String, dynamic>);
extractedData.myChannels[0].id
extractedData.myChannels[0].name
extractedData.myChannels[0].imageUrl

for (var ch in extractedData.myChannels){
 print(ch.id);
 print(ch.name);
 print(ch.imageUrl);
}

Why does the following JSON not deserialize properly?

copy iconCopydownload iconDownload
//local or method
D3Point toD3Point(string json) { 
  var j = JsonConvert.DeserializeObject<Dictionary<string, double>>(json); 
  return new D3Point(j["X"],j["Y"],j["Z"]);
}
        
D3Point coord = toD3Point(cJson);
new[]{ JsonConvert.DeserializeObject<Dictionary<string, double>>(cJson) }.Select(j => new D3Point(j["X"],j["Y"],j["Z"]).First();
-----------------------
//local or method
D3Point toD3Point(string json) { 
  var j = JsonConvert.DeserializeObject<Dictionary<string, double>>(json); 
  return new D3Point(j["X"],j["Y"],j["Z"]);
}
        
D3Point coord = toD3Point(cJson);
new[]{ JsonConvert.DeserializeObject<Dictionary<string, double>>(cJson) }.Select(j => new D3Point(j["X"],j["Y"],j["Z"]).First();

CMakeLists - How to include a directory of source and header files?

copy iconCopydownload iconDownload
# Create and import the library targets
add_subdirectory(Metriful)

# Publicly link `foo` to `main` component
target_link_libraries(main PUBLIC metriful)
-----------------------
set(EXTRA_COMPONENT_DIRS "Metriful")
- main
   main.cpp 
   your.h
- components
   -Metriful
       Metriful.cpp 
       Metriful.h
idf_component_register(
 SRCS "Metriful/MetrifulC.cpp" "Metriful/MetrifulA.cpp" 
 INCLUDE_DIRS "."
 REQUIRES arduino
)
 REQUIRES Metriful
-----------------------
set(EXTRA_COMPONENT_DIRS "Metriful")
- main
   main.cpp 
   your.h
- components
   -Metriful
       Metriful.cpp 
       Metriful.h
idf_component_register(
 SRCS "Metriful/MetrifulC.cpp" "Metriful/MetrifulA.cpp" 
 INCLUDE_DIRS "."
 REQUIRES arduino
)
 REQUIRES Metriful
-----------------------
set(EXTRA_COMPONENT_DIRS "Metriful")
- main
   main.cpp 
   your.h
- components
   -Metriful
       Metriful.cpp 
       Metriful.h
idf_component_register(
 SRCS "Metriful/MetrifulC.cpp" "Metriful/MetrifulA.cpp" 
 INCLUDE_DIRS "."
 REQUIRES arduino
)
 REQUIRES Metriful
-----------------------
set(EXTRA_COMPONENT_DIRS "Metriful")
- main
   main.cpp 
   your.h
- components
   -Metriful
       Metriful.cpp 
       Metriful.h
idf_component_register(
 SRCS "Metriful/MetrifulC.cpp" "Metriful/MetrifulA.cpp" 
 INCLUDE_DIRS "."
 REQUIRES arduino
)
 REQUIRES Metriful

How to generate and display coverage when running tests with Pongo for custom Kong API Gateway plugins written in Lua

copy iconCopydownload iconDownload
"/bin/sh" "-c" "bin/busted --coverage --helper=bin/busted_helper.lua ${busted_params[*]} ${busted_files[*]};luacov;cat luacov.report.out"
    && luarocks install busted-htest \
    && luarocks install luacov \
[...]
==============================================================================
Summary
==============================================================================

File                                                                              Hits  Missed Coverage
-------------------------------------------------------------------------------------------------------
/kong-plugin/kong/plugins/myplugin/schema.lua                                     105   1      99.06%
/kong-plugin/spec/myplugin/01-schema_spec.lua                                     199   5      97.55%
[...]
-----------------------
"/bin/sh" "-c" "bin/busted --coverage --helper=bin/busted_helper.lua ${busted_params[*]} ${busted_files[*]};luacov;cat luacov.report.out"
    && luarocks install busted-htest \
    && luarocks install luacov \
[...]
==============================================================================
Summary
==============================================================================

File                                                                              Hits  Missed Coverage
-------------------------------------------------------------------------------------------------------
/kong-plugin/kong/plugins/myplugin/schema.lua                                     105   1      99.06%
/kong-plugin/spec/myplugin/01-schema_spec.lua                                     199   5      97.55%
[...]
-----------------------
"/bin/sh" "-c" "bin/busted --coverage --helper=bin/busted_helper.lua ${busted_params[*]} ${busted_files[*]};luacov;cat luacov.report.out"
    && luarocks install busted-htest \
    && luarocks install luacov \
[...]
==============================================================================
Summary
==============================================================================

File                                                                              Hits  Missed Coverage
-------------------------------------------------------------------------------------------------------
/kong-plugin/kong/plugins/myplugin/schema.lua                                     105   1      99.06%
/kong-plugin/spec/myplugin/01-schema_spec.lua                                     199   5      97.55%
[...]
-----------------------
FROM kong-pongo-test:2.3.2
USER root
RUN luarocks install luacov
WORKDIR /kong-plugin
COPY . .
#!/bin/sh
busted --coverage spec/unit
luacov
cat luacov.report.out
docker build -f spec/unit/docker/Dockerfile -t my-coverage .
docker run my-coverage sh spec/unit/docker/run.sh
-----------------------
FROM kong-pongo-test:2.3.2
USER root
RUN luarocks install luacov
WORKDIR /kong-plugin
COPY . .
#!/bin/sh
busted --coverage spec/unit
luacov
cat luacov.report.out
docker build -f spec/unit/docker/Dockerfile -t my-coverage .
docker run my-coverage sh spec/unit/docker/run.sh
-----------------------
FROM kong-pongo-test:2.3.2
USER root
RUN luarocks install luacov
WORKDIR /kong-plugin
COPY . .
#!/bin/sh
busted --coverage spec/unit
luacov
cat luacov.report.out
docker build -f spec/unit/docker/Dockerfile -t my-coverage .
docker run my-coverage sh spec/unit/docker/run.sh

Parse JSON with missing fields using cjson Lua module in Openresty

copy iconCopydownload iconDownload
resty -e 'local t = {foo = 1}; print(t["foo"]); print(t["foo"]["bar"])'
1
ERROR: (command line -e):1: attempt to index field 'foo' (a number value)
stack traceback:
    ...
  resty -e 'print(require("cjson").decode("[1, 2, 3"))' 
  ERROR: (command line -e):1: Expected comma or array end but found T_END at character 9
  stack traceback:
      ...
resty -e 'print(require("cjson.safe").decode("[1, 2, 3"))'
nilExpected comma or array end but found T_END at character 9
-----------------------
resty -e 'local t = {foo = 1}; print(t["foo"]); print(t["foo"]["bar"])'
1
ERROR: (command line -e):1: attempt to index field 'foo' (a number value)
stack traceback:
    ...
  resty -e 'print(require("cjson").decode("[1, 2, 3"))' 
  ERROR: (command line -e):1: Expected comma or array end but found T_END at character 9
  stack traceback:
      ...
resty -e 'print(require("cjson.safe").decode("[1, 2, 3"))'
nilExpected comma or array end but found T_END at character 9
-----------------------
resty -e 'local t = {foo = 1}; print(t["foo"]); print(t["foo"]["bar"])'
1
ERROR: (command line -e):1: attempt to index field 'foo' (a number value)
stack traceback:
    ...
  resty -e 'print(require("cjson").decode("[1, 2, 3"))' 
  ERROR: (command line -e):1: Expected comma or array end but found T_END at character 9
  stack traceback:
      ...
resty -e 'print(require("cjson.safe").decode("[1, 2, 3"))'
nilExpected comma or array end but found T_END at character 9

OpenResty - No response when making a http call with lua

copy iconCopydownload iconDownload
resolver 8.8.8.8;  # use Google's public DNS nameserver
return ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
-----------------------
resolver 8.8.8.8;  # use Google's public DNS nameserver
return ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
-----------------------
resolver 8.8.8.8;  # use Google's public DNS nameserver
return ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)

cJSON_Delete(); causes free(): invalid pointer: 0xb5db1e18

copy iconCopydownload iconDownload
cJSON_Delete(body);

Community Discussions

Trending Discussions on cJSON
  • Fibaro Home Center 2 requesting https prices and timestamps question
  • Dynamically fetching the Json key value in Lua
  • Iterating through a cJSON Array alternatively
  • How can I convert an int (which represents an decimal without its decimal places) to a double in c?
  • Send Json Payload to californium server
  • HTTPSConnectionPool error when trying to install gtest with conan
  • How to handle POST request with JSON payload on ESP32 server?
  • Parsing json array response / flutter
  • cJSON_Delete() and cJSON_free()
  • Why does the following JSON not deserialize properly?
Trending Discussions on cJSON

QUESTION

Fibaro Home Center 2 requesting https prices and timestamps question

Asked 2022-Apr-08 at 23:43

I have a script which I wrote on Lua, that worked to get the prices and timestamps, but it won't work on fibaro HC2.

My Lua code:

local requests = require('requests')
local json = require('cjson')
local socket = require('socket.http')
local https = require('ssl.https')

Tomorrow = os.date("%Y-%m-%d",os.time()+24*60*60)
Yesterday = os.date("%Y-%m-%d",os.time()-24*60*60)
URL = "https://dashboard.elering.ee/api/nps/price?start=2021-12-09T20%3A59%3A59.999Z&end=2021-12-10T20%3A59%3A59.999Z"
first_url = "https://dashboard.elering.ee/api/nps/price?start="
mid_url = "T20%3A59%3A59.999Z&end="
end_url = "T20%3A59%3A59.999Z"

URL = first_url .. Yesterday .. mid_url .. Tomorrow .. end_url
print(URL)

Times = {}
Prices = {}

local body, code, headers, status = https.request(URL)

if body then
  --print(body)
  else
  --print(code)
  end

t = json.decode(body)
for _, v in ipairs(t.data.ee) do table.insert(Times, v.timestamp) end
for _, v in ipairs(t.data.ee) do table.insert(Prices, v.price) end

print(Times[1])
print(Prices[1])

Output:

1649278800.0
98.6

But on HC2 the output is:

[DEBUG] 08:06:18: 2022-04-08 08:06:18.658376 [ fatal] Unknown exception: /opt/fibaro/scenes/1.lua:7: attempt to call global 'require' (a nil value)

What am I doing wrong and how can I get it to work?

ANSWER

Answered 2022-Apr-08 at 23:43

As Egor suggested, Fibaro sandboxes their Lua environment. A full list of what is removed is listed at https://manuals.fibaro.com/knowledge-base-browse/blocked-lua-commands/, but it includes require, dofile, load, loadfile, loadstring, several functions in the os library, and the entire io and package library.

That effectively requires all of your code to be contained in a single file, with no access to modules, packages, or libraries other than the remaining parts of the standard library, which means you simply can't do what you're trying to do here.

Source https://stackoverflow.com/questions/71792067

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install cJSON

You can download it from GitHub.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.