cscanf

How to parse json using sscanf in C?


I have the following string in the form of json:

{
   "num":1,
   "data":{
      "city":"delhi"
   }
}

I need to get the value of "num" key using sscanf. Here is my attempt. I know it's incorrect. But I don't know how to do it.

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

int main(void) {
    
    char *str = "{\"num\":1,\"data\":{\"city\":\"delhi\"}}";
    char *ret = malloc(sizeof(char) * 10);
    
    sscanf(str, "{\"num\":%s, %s" , ret);
    
    printf("%s", ret);
    return 0;
}

Any suggestions?


Solution

  • sscanf(str, "{\"num\":%s, %s" , ret);
    

    is wrong, first you have two "%s" but you give only one location to save string (ret), and it does not extract as you expect

    you want

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
    
        char *str = "{\"num\":1,\"data\":{\"city\":\"delhi\"}}";
        char *ret = malloc(10); /* by definition sizeof(char) is 1 */
    
        if (sscanf(str, "{\"num\":%9[^,]" , ret) == 1)
            printf("value is '%s'\n", ret);
    
        free(ret);
        return 0;
    }
    

    Compilation and execution

    /tmp % gcc -Wall p.c
    /tmp % ./a.out
    value is '1'
    /tmp % 
    

    but to use scanf to parse is limited