How to create and print a JSON string in C++

3 Answers

0 votes
#include <iostream>
#include <string>

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

    std::cout << json << std::endl;
}


/*
run:

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

*/

 



answered 17 hours ago by avibootz
0 votes
#include <iostream>
#include <string>
#include <sstream>

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

    std::stringstream ss(json);
    std::string part;

    while (std::getline(ss, part, ',')) {
        std::cout << part << std::endl;
    }
}



/*
run:

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

*/

 



answered 16 hours ago by avibootz
0 votes
#include <iostream>
#include <string>

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

    int indent = 0;

    for (size_t i = 0; i < json.size(); ++i) {
        char c = json[i];

        if (c == '{' || c == '[') {
            std::cout << std::string(indent, ' ') << c << "\n";
            indent += 2;
        }
        else if (c == '}' || c == ']') {
            indent -= 2;
            std::cout << std::string(indent, ' ') << c << "\n";
        }
        else if (c == ',') {
            std::cout << c << "\n";
        }
        else {
            std::cout << std::string(indent, ' ') << c;

            while (i + 1 < json.size() &&
                   json[i + 1] != ',' &&
                   json[i + 1] != '{' &&
                   json[i + 1] != '}' &&
                   json[i + 1] != '[' &&
                   json[i + 1] != ']' ) {
                i++;
                std::cout << json[i];
            }
            std::cout << "\n";
        }
    }
}



/*
run:

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

*/

 



answered 16 hours ago by avibootz

Related questions

3 answers 289 views
3 answers 246 views
1 answer 225 views
2 answers 191 views
...