2

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
}
]
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
ashu nath
  • 21
  • 1
  • 2

2 Answers2

4

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.

Shubham
  • 628
  • 1
  • 9
  • 19
  • 1
    He says he doesnt want to use libraries – Moritz Schmidt Apr 29 '19 at 10:54
  • oh, sorry I missed it. Then in this case using [strstr](https://linux.die.net/man/3/strstr) may be helpful in parsing string on our own – Shubham Apr 29 '19 at 11:00
  • @shubham Can you please elaborate ? I am calculating data in the code and want to update it in json file. – ashu nath Apr 29 '19 at 17:31
  • Can you clarify whether you want to update json to a file or just parse it? [cJSON_Test](https://github.com/shubhamdpatil/cJSON_Test), here is the test code for parsing as well as updating the json read/update from/to file. And usage of strstr and strtok is explained in belowed answer by Keine Lust – Shubham Apr 30 '19 at 05:26
3

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;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94