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
}
]
4
  • 5
    Are you sure, implementing a JSON parser will be simpler than just using an existing lib? Commented Apr 29, 2019 at 10:43
  • Is the JSON always in the same format with the same number of labels? Commented Apr 29, 2019 at 10:59
  • @KeineLust Yes, in this particular case only frequency changes. Commented Apr 29, 2019 at 17:30
  • @Gerhardh , not sure. Commented Apr 29, 2019 at 17:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

He says he doesnt want to use libraries
oh, sorry I missed it. Then in this case using strstr may be helpful in parsing string on our own
@shubham Can you please elaborate ? I am calculating data in the code and want to update it in json file.
Can you clarify whether you want to update json to a file or just parse it? 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
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.