How to create and print a JSON string in C

3 Answers

0 votes
#include <stdio.h>

int main() {
    const char *json =
        "{"
        "\"name\": \"Tor\","
        "\"age\": 35,"
        "\"skills\": [\"C/C++\", \"Java\", \"Python\"]"
        "}";

    printf("%s\n", json);
    
    return 0;
}



/*
run:

{"name": "Tor","age": 35,"skills": ["C/C++", "Java", "Python"]}

*/

 



answered 19 hours ago by avibootz
0 votes
#include <stdio.h>
#include <string.h>

int main() {
    char json[] =
        "{"
        "\"name\": \"Tor\","
        "\"age\": 35,"
        "\"skills\": [\"C/C++\", \"Java\", \"Python\"]"
        "}";

    char *token = strtok(json, ",");

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, ",");
    }

    return 0;
}



/*
run:

{"name": "Tor"
"age": 35
"skills": ["C/C++"
 "Java"
 "Python"]}

*/

 



answered 19 hours ago by avibootz
edited 18 hours ago by avibootz
0 votes
#include <stdio.h>

int main() {
    const char *json =
        "{"
        "\"name\": \"Tor\","
        "\"age\": 35,"
        "\"skills\": [\"C/C++\", \"Java\", \"Python\"]"
        "}";

    int indent = 0;

    for (int i = 0; json[i] != '\0'; i++) {
        char c = json[i];

        if (c == '{' || c == '[') {
            printf("%*s%c\n", indent, "", c);
            indent += 2;
        }
        else if (c == '}' || c == ']') {
            indent -= 2;
            printf("%*s%c\n", indent, "", c);
        }
        else if (c == ',') {
            printf("%c\n", c);
        }
        else {
            printf("%*s%c", indent, "", c);

            // print until next comma or brace
            while (json[i+1] != ',' &&
                   json[i+1] != '}' &&
                   json[i+1] != ']' &&
                   json[i+1] != '\0') {
                i++;
                printf("%c", json[i]);
            }
            printf("\n");
        }
    }

    return 0;
}




/*
run:

{
  "name": "Tor"
,
  "age": 35
,
  "skills": ["C/C++"
,
   "Java"
,
   "Python"
]
  }

*/

 



answered 19 hours ago by avibootz

Related questions

3 answers 289 views
3 answers 246 views
1 answer 140 views
1 answer 158 views
1 answer 166 views
...