ashu nath
ashu nath

Reputation: 21

JSON Parser using c

I have to parse a JSON using c code(not lib because want to make things look as simple as possible) for some real-time handling. Below is data need to be parsed which I will be getting from some calculation generated by the code itself. Please help me out.

[
{
    "Letter": 0 ,
    "Freq": 2858    
},
.
.
.
.
.
{
    "Letter" : 31,
    "Freq" : 0
}
]

Upvotes: 2

Views: 11207

Answers (2)

David Ranieri
David Ranieri

Reputation: 41046

It seems that you only want to extract the "Freq" value, in this case this code is enough:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *str = "[{\"Letter\": 0 ,\"Freq\": 2858},{\"Letter\" : 31,\"Freq\" : 0}]";

int main(void)
{
    char *ptr = str;
    long value;

    while (ptr) {
        ptr = strstr(ptr, "\"Freq\"");
        if (ptr == NULL) {
            break;
        }
        ptr = strchr(ptr, ':');
        if (ptr == NULL) {
            break;
        }
        ptr++;
        value = strtol(ptr, &ptr, 10);
        if (*ptr != '}') {
            break;
        }
        ptr++;
        printf("%lu\n", value);
    }
    return 0;
}

Upvotes: 3

Shubham
Shubham

Reputation: 646

These are two C libraries I have used.

  1. https://github.com/DaveGamble/cJSON : this can parse your string and can prepare json strings.

  2. https://github.com/zserge/jsmn : this is only for parsing json strings.

Both libraries are well documented and has test code available.

Upvotes: 4

Related Questions