1

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?

6
  • 5
    Don't use sscanf. JSON is too complex for that. Use a proper JSON parser instead. Commented Apr 24, 2020 at 10:06
  • 1
    There are two possibilities: use a dirty hack, if you are sure, that the string is exactly formatted this way int num = atoi(strchr(str, ':')+1); or use a json parser, if the string can vary. Commented Apr 24, 2020 at 10:08
  • @OliverMason, I have no other option than sscanf and regex. My entire implementation is in C. I can't even use third party plugins, libraries etc. Commented Apr 24, 2020 at 10:10
  • 1
    @Ctx, I think your approach would work, since my string has a fixed format. Thanks a lot. Commented Apr 24, 2020 at 10:12
  • 3
    Using sscanf for this is a terrible idea. Here's a very lightweight JSON parser written entirely in ANSI (portable) C. You can just drop it into your project: github.com/udp/json-parser Commented Apr 24, 2020 at 10:14

1 Answer 1

3
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

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

2 Comments

Just what I wanted. Thank you so much. I am using sscanf because my json is of fixed length and fixed format. So, this would work.
@no_one so fine. When you read/extract using one of the scanf function I recommend you to always check the return value to know how much elements was got, and when it is a string to limit the length where scanf will write (here 9 even the string is sized 10 because the ending null character is not count even written)

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.