Parsing JSON using C [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I'm trying to find a good way to parse JSON in C. I really don't need a huge library or anything, I would rather have something small and lightweight with a bare minimum of features, but good documentation.
Does anyone have anything they can point me to?

Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).
There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.

cJSON has a decent API and is small (2 files, ~700 lines). Many of the other JSON parsers I looked at first were huge... I just want to parse some JSON.
Edit: We've made some improvements to cJSON over the years.

NXJSON is full-featured yet very small (~400 lines of code) JSON parser, which has easy to use API:
const nx_json* json=nx_json_parse_utf8(code);
printf("hello=%s\n", nx_json_get(json, "hello")->text_value);
const nx_json* arr=nx_json_get(json, "my-array");
int i;
for (i=0; i<arr->length; i++) {
const nx_json* item=nx_json_item(arr, i);
printf("arr[%d]=(%d) %ld\n", i, (int)item->type, item->int_value);
}
nx_json_free(json);

Jsmn is quite minimalistic and has only two functions to work with.
https://github.com/zserge/jsmn

You can have a look at Jansson
The website states the following:
Jansson is a C library for encoding, decoding and manipulating JSON data. It features:
Simple and intuitive API and data model
Can both encode to and decode from JSON
Comprehensive documentation
No dependencies on other libraries
Full Unicode support (UTF-8)
Extensive test suite

I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.
Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.
The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).
JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.

Do you need to parse arbitrary JSON structures, or just data that's specific to your application. If the latter, you can make it a lot lighter and more efficient by not having to generate any hash table/map structure mapping JSON keys to values; you can instead just store the data directly into struct fields or whatever.

Related

Getting data from a .json file in c [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I'm trying to find a good way to parse JSON in C. I really don't need a huge library or anything, I would rather have something small and lightweight with a bare minimum of features, but good documentation.
Does anyone have anything they can point me to?
Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).
There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.
cJSON has a decent API and is small (2 files, ~700 lines). Many of the other JSON parsers I looked at first were huge... I just want to parse some JSON.
Edit: We've made some improvements to cJSON over the years.
NXJSON is full-featured yet very small (~400 lines of code) JSON parser, which has easy to use API:
const nx_json* json=nx_json_parse_utf8(code);
printf("hello=%s\n", nx_json_get(json, "hello")->text_value);
const nx_json* arr=nx_json_get(json, "my-array");
int i;
for (i=0; i<arr->length; i++) {
const nx_json* item=nx_json_item(arr, i);
printf("arr[%d]=(%d) %ld\n", i, (int)item->type, item->int_value);
}
nx_json_free(json);
Jsmn is quite minimalistic and has only two functions to work with.
https://github.com/zserge/jsmn
You can have a look at Jansson
The website states the following:
Jansson is a C library for encoding, decoding and manipulating JSON data. It features:
Simple and intuitive API and data model
Can both encode to and decode from JSON
Comprehensive documentation
No dependencies on other libraries
Full Unicode support (UTF-8)
Extensive test suite
I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.
Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.
The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).
JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.
Do you need to parse arbitrary JSON structures, or just data that's specific to your application. If the latter, you can make it a lot lighter and more efficient by not having to generate any hash table/map structure mapping JSON keys to values; you can instead just store the data directly into struct fields or whatever.

Small libc for embedded systems [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I am looking for a small libc for embedded use with freertos on a ARM7 microcontroller.
I have looked at newlib, but it is a bit too complex for my needs. Newlib calls malloc() in
a number of functions (e.g. printf()), which is not good for small embedded realtime systems.
Does anyone know of a small, portable, open source libc implementation that will fit my application?
PDCLib might fit your needs. It's still incomplete [broken link], though, and probably in need of a lot more real-world testing. Its author goes by DevSolar here on SO.
update 2012-11-01: As of 2012-08-14, development has been taken over by Owen Shepherd, complete with a new homepage and bitbucket repository [broken link, use this one].
update 2015-10-31: The dedicated website seems to be dead, but the code can still be found on bitbucket. The last commit to that repository happened 2014-11-24.
update 2016-07-12: The website is back up, and DevSolar started committing again on 2016-03-01.
I use newlib on my Cortex_M3 with 32kB RAM, and to eliminate the malloc() you can use siprintf() or sniprintf().
Pro: No more calls to malloc().
Con: It does not suport formatting float and double, and is not really portable this way.
If you use newlib and do not implement the sbrk syscall, then any function you use that requires malloc will generate a linker error, which will prevent you from inadvertently using a call that requires dynamic memory . So I would suggest that you do that, and then simply avoid those functions that cause the linker error. You can modify or override any library functions you do not wish to use.
printf() is not good for small embedded realtime systems!
Actually it is worse than malloc in many ways. Variable argument lists, very complex formatting, float number support when you don't need it etc etc. printf() comes with an enormous overhead, and the compiler will not be able to reduce it, as every parameter passed to it is evaluated in runtime.
printf() is perhaps ok for hobbyists and beginners still learning C. But if you are a professional programmer, you really ought to write your own serial monitor / LCD routines. You will dramatically improve the program performance and flash consumption.
I had similar needs and found that klibc fit it quite well. The only downside (for commercial use) is that the distribution includes a few GPL-licensed files, even though most of it is BSD-licensed. I have hacked a minimal version of it here.
This is even more limited than PDCLib, and suitable if you just need a few basic functions such as printf and strtok. Compiles to just 4kB with all functions included.
You might want to look into the Embedded Artistry libc, which promises to be minimal and well-tested. It includes a malloc-free printf(). Disclaimer: I have not used it, but it appears well-structured and actively developed.
You can check out the LGPL µClibc, which is supposed to be close to glibc but much more suited to embedded systems.
It also has a page referencing other open source C libraries, including newlib and eCos, which may be more suited for non-Linux environments.
Look into uClibc and EGLIBC, perhaps.

Standard data structure library in C? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed last year.
Improve this question
I am looking for standard tried and tested library in C language (Windows platform) which implements data structures like stacks, queues, trees etc.
I would prefer to have a source code along with it. Writing a library on my own is possible; however, I feel it may be better to opt for some industry standard implementation which may be optimised and less buggy.
Compiler is Visual Studio 2005/2008.
Glib
Download Glib for Windows here
GDSL. As per the documents, it is pure ANSI C and should work with Visual C++.
C-generic-library
Kompimi. C data structure library, with an emphasis on collections. Comes with Visual Studio project files.
Have you checked out qLibc? It's an opensource C implementation that provides various types of data strucutre such as hash table, linked list, queue, stack...
As of today, from it's website I see it has following feature set:
Containers
List --- Doubly Linked List.
List Table --- KEY/VALUE paired table implemented on linked-list.
Hash Table --- Hash based KEY/VALUE paired table.
Static Hash Table --- Static(array/mmapped/shared) memory based KEY/VALUE paired table.
Vector --- implements a growable array of elements.
Queue --- FIFO(First In First Out) implementation.
Stack --- LIFO(Last In First Out) implementation.
General utilities.
String
I/O
File
IPC, Semaphore Shared-memory
En/decoders
Hashes
System
Time
Extensions
INI-style Configuration File Parser.
Apache-style Configuration File Parser.
Rotating File Logger.
HTTP client.
Database(MySQL) interface.
In each container implementation, it clearly explains internal data structure at the top of code. So it would be helpful for you to catch the implementation ideas.
The code can be found at https://github.com/wolkykim/qlibc
Hope this helps. (Please do vote if this helps, I need some points. Thanks :)
Check out cbase. Its LGPL (most of the other libraries are GPL) if license is something that concerns you.
My only comment is that it requires C99 or GCC. It uses variadic macros, which aren't C89 compatible. It should compile fine under VC2005/2008.
cbase is a C library of useful functions that simplify systems software development on System V UNIX. The library includes routines for memory management, string parsing, filesystem traversal, subprocess execution, I/O, as well as implementations of common data structures such as linked lists, hash tables, stacks, and queues. The library also includes a high-level interface to Berkeley sockets, and an implementation of a scheduler which has functionality very similar to that of the cron daemon. Note: cbase was formerly known as CFL.
You might want to have a look at http://www.liblfds.org/

AST from C code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I want to perform some transformations on C source code. I need a tool on linux that generates a complete AST from the source code so that I can apply my transformations on this AST and then convert it back to the C source code. I tried ELSA but it is not getting compiled. (I am using Ubuntu 8.4). Can anyone suggest a better tool/application?
I would recommend clang. It has a fairly complete C implementation with most gcc extensions, and the code is very understandable. Their C++ implementation is incomplete, but if you only care about generating ASTs from C code that should be fine. Depending on what you want to do you can either use clang as a library and work with the ASTs directly, or have clang dump them out to console.
See pycparser - a pure-Python AST generator for C.
There are two projects that I'm aware of and that you could find useful:
CIL
Transformers
They both parse a standard C source code to allow further analisys and transformation. I've not used them so you have to check for yourself if they fit your needs.
The suggestion of using GCC is also valid, of course. I know there's not much documentation on this aspect of gcc, though.
To get AST XML output you can try to use cscan from MarpaX::Languages::C::AST. The output will look like:
xml
<cscan>
<typedef_hash>
<typedef id="GLenum" before="unsigned int" after="" file="/usr/include/GL/gl.h"/>
...
www.antlr.org
http://ctool.sourceforge.net/
Our DMS Software Reengineering Toolkit has been used on huge C systems, parsing, analyzing, transforming, and regenerating C code. Runs on Windows, and will run on Linux under Wine, but it does handle Linux-style (GCC) C code.
I can't emphasize enough the ability to round-trip the C source code: parse, build trees, transform, regenerate compilable C code with the comments and either prettyprinted or with the original programmer's indentation. Few of the other answers here suggest systems that can do that robustly.
The fact that DMS is designed to carry out program transformations (as opposed to other systems suggested in answers here) is also a great advantage. DMS provide tree-pattern matches and rewrites; it augments this with full control and data flow analyis to be used to extend the conditions that you'd like to match. A tool intending to be a compiler is just that, and you'll have a very hard time persuading it not to be a compiler, and an instead to be a transformation engine as the OP requested.
See https://stackoverflow.com/a/2173477/120163 for example ASTs produced by DMS.
I've done small amounts of work on source-to-source transformations and I found CIL to be very powerful for this task. CIL has the advantage of being a framework specifically designed for static source analysis and transformation. It can also process code with any amount of ugly GCC specific extensions(It's been used to process the Linux kernel, as one example.) Unfortunately, it is written in OCAML, and analyses/transformations built using it must also be writtne in OCAML, which might be problematic if you've never used it.
Alternatively, clang is supposed to have a relatively easily-hackable codebase and it can certainly be used to produce C AST's.
You can try generate AST (Abstract Syntax Tree) using Lexx and Yacc on Linux:
lex and yacc
from lex and yacc to ast
"I tried ELSA but it is not getting
compiled. (I am using Ubuntu 8.4)"
The Elkhound and Elsa source code, version 2005.08.22b from scottmcpeak.com/elkhound/ is outdated (old C++ style .h header files).
Elsa is working and part of Oink: http://www.cubewano.org/oink/#Gettingthecode
I have just got it working now under Ubuntu 9.10.
How about taking gcc and writing a custom backend for it? I've never done it nor even worked on gcc source code, so I don't know how hard it would be.

Parse C files [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I am looking for a Windows based library which can be used for parsing a bunch of C files to list global and local variables. The global and local variables may be declared using typedef. The output (i.e. list of global and local variables) can then be used for post processing (e.g. replacing the variable names with a new name).
Is such a library available?
Some of the methods available:
Elsa: The Elkhound-based C/C++ Parser
CIL - Infrastructure for C Program Analysis and Transformation
Sparse - a Semantic Parser for C
clang: a C language family frontend for LLVM
pycparser: C parser and AST generator written in Python
Alternately you could write your own using lex and yacc (or their kin- flex and bison) using a public lex specification and a yacc grammar.
Possibly overkill, but there's a complete ANSI C parser written with Boost.Spirit:
http://spirit.sourceforge.net/repository/applications/c.zip
Maybe you'll be able to model it to suit your needs.
Parsing C is lot harder than it looks, when you take into
account different dialects, preprocessor directives,
the need for type information while parsing, etc.
People that tell you "just use lex and yacc" have
clearly not done a production C parser.
A tool that can do this is our C front end
It addresses all of the above issues.
On completion, it has a complete, navigable symbol table
with all identifiers and corresponding type information.
Listing global and local variables would be trivial with this.
I'm the architect behind Semantic Designs.
I don't know if it offers a library, but have a look at CTAGS.
If it is plain C, lex and yacc are your friends, but you need to take on account C preprocessor - source files with unexpanded macros typically are do not comply with C syntax so parser, written with K&R grammar in mind, most likely will fail.
If you decide to parse the output of preprocessor, be prepared that your parser will fail due to "extensions" of your particular compiler, because very likely standard library headers use them. At least this the the case with GCC.
I had this with GCC and finally decided to achieve my goal using different approach. If you just need to change names for variables, regular expressions will do fine, and there is no need to build a full parser, IMHO. If your goal is just to collect data, the ultimate source of data is debug information. There are ways to get debug information out of binary - for ELF executables with DWARF there is libdwarf, for Windows-land (COFF ?) should be something as well. Probably you can use some existing tools to get debug information about binary - again, I know nothing about Windows, you need to investigate.
I recently read about a win32-based system that looked at the debugging information in COFF dlls:
http://www.drizzle.com/~scottb/gdc/fubi-paper.htm
Maybe gnu project cflow http://www.gnu.org/software/cflow/ ?

Resources