Home > Software engineering >  nLohmann lib in C from raw http data
nLohmann lib in C from raw http data

Time:11-23

I have raw http data

char text[] = R"({\"ID\": 123,\"Name\": \  
        "Afzaal Ahmad Zeeshan\",\"Gender\":   
        true, \"DateOfBirth\": \"1995-08-29T00:00:00\"})";

I am using Json nlohmann lib , it gives me the parse error and if i tried the following then it parse

R"({"happy": true, "pi": 3.141})"

Is the nlohmann does not parse http raw data ?

CodePudding user response:

You are using a raw string literal so drop the backslashes:

char text[] = R"({
    "ID": 123,
    "Name": "Afzaal Ahmad Zeeshan",
    "Gender": true,
    "DateOfBirth": "1995-08-29T00:00:00"
})";

Full example:

#include <nlohmann/json.hpp>

#include <iomanip>
#include <iostream>

using json = nlohmann::json;

int main() {
    char text[] = R"({
        "ID": 123,
        "Name": "Afzaal Ahmad Zeeshan",
        "Gender": true,
        "DateOfBirth": "1995-08-29T00:00:00"
    })";
    
    char text2[] = R"({"happy": true, "pi": 3.141})";
    
    json obj1, obj2;
    
    try {
        obj1 = json::parse(text);
        obj2 = json::parse(text2);

        // print the json objects:
        std::cout << std::setw(2) << obj1 << '\n'
                  << obj2 << '\n';
    }
    catch(const json::parse_error& ex) {
        std::cerr << "parse error at byte " << ex.byte << std::endl;
    }
}

Possible output:

{
  "DateOfBirth": "1995-08-29T00:00:00",
  "Gender": true,
  "ID": 123,
  "Name": "Afzaal Ahmad Zeeshan"
}
{"happy":true,"pi":3.141}

Demo

  • Related