Parsing string

Say I have a string with json like data such as "{"flight_number":65,"mission_name":"Telstar 19V","mission_id":["F4F83DE"],"launch_year":"2018""

How can I extract the values (65, "Telstar 19V", "2018")so that I can store them in my struct?

I would just use a json library. For example,
https://github.com/nlohmann/json

See the README.md for instructions and examples. It can be used as a single header-file library.
Last edited on
I agree, however, how could I perform this parsing without using a JSON library?
for very simple xml/json/etc markup files with known format etc you can just do getlines with a ':' delimiter or find/substring or the like. Parsing tools can be way overkill if you just need to get a number from a field out of a 2 line api response etc. If doing it directly becomes any kind of real work, though, swap out to the library.
Last edited on
Your structure is:

{
  "A" :   B   ,
  "C" :  "D"  ,
  "E" : ["F"] ,
  "G" :  "H"
}


Can commas appear inside the quotes?
Can colons appear inside the quotes?
Can escaped quotes appear inside the quotes?
Are the fields always in this order with no other intervening fields?

Assuming "no", "no", "no", "yes", then:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void trim_quotes(string& s)
{
    if (!s.empty() && s.front() == '"') s.erase(0, 1);
    if (!s.empty() && s.back()  == '"') s.pop_back();
}

int main()
{
    string line {"{\"flight_number\":65,"
                 "\"mission_name\":\"Telstar 19V\","
                 "\"mission_id\":[\"F4F83DE\"],"
                 "\"launch_year\":\"2018\"}"};
    istringstream ss(line);

    char ch;
    ss >> ch; // eat initial '{'

    int flight_number;
    string mission_name, year, id;

    getline(ss, id, ':');
    ss >> flight_number;
    ss >> ch; // eat ','

    getline(ss, id, ':');
    getline(ss, mission_name, ',');
    trim_quotes(mission_name);

    getline(ss, id, ','); // eat entire "mission_id" line
    
    getline(ss, id, ':');
    getline(ss, year);
    if (!year.empty() && year.back() == '}')
        year.pop_back();
    trim_quotes(year);

    cout << flight_number << '\n' << mission_name << '\n' << year << '\n';
}

Topic archived. No new replies allowed.