Json: very basic: fetching string value/content without quotes

Created on 3 Dec 2017  路  5Comments  路  Source: nlohmann/json

This is kind of a usage issue and not a bug/feature request. I could be overlooking something trivial as I am very new to the library; if this is the case, please point in the right direcion/documentation.

  • What is the issue you have?

When printing/using a value from a string element, the string is quoted:

$ ./test 
"value"
  • Please describe the steps to reproduce the issue. Can you provide a small but working code example?
    #include <iostream>
    #include "json.hpp"
    using json = nlohmann::json;
    int main(int argc, char *argv[])
    {
        json j = R"({"one": "value"})"_json;
        std::cout << j["one"] << '\n';
    }
  • What is the expected behavior?

Printing/fetching value as opposed to "value".

I understand that this could be a simple matter of picking out a substring, but searching in the documentation and existing issues (closed and open), I didn't find an idiomatic way of simply extracting the original string (no quotes as quotes are not escaped in the JSON blob).

GCC (7.2.0).

  • Did you use a released version of the library or the version from the develop branch?

Git master, cc937deaf6430a5a02d366bb3cb7140693f20c0e

question proposed fix

Most helpful comment

The type of j["one"] is json, not std::string, so when you print it, it's quoted. If you want the bare string, you need to specify that: j["one"].get<std::string>().

All 5 comments

One thing I just noticed is that this could be a non-issue at all.

In another code I'm working on, checking with gdb:

(gdb) p d
$1 = "2017-11-30"
(gdb) p d.c_str()
$3 = 0x63c958 "2017-11-30"
(gdb) x/12xc d.c_str()
0x63c958:   50 '2'  48 '0'  49 '1'  55 '7'  45 '-'  49 '1'  49 '1'  45 '-'
0x63c960:   51 '3'  48 '0'  0 '\000'    0 '\000'

There weren't quotes. Only when std::cout'ing them.

I must be overlooking something very obvious.

The type of j["one"] is json, not std::string, so when you print it, it's quoted. If you want the bare string, you need to specify that: j["one"].get<std::string>().

You could also write

std::string s = j["one"];

for an implicit conversion which avoids you writing .get<std::string>().

Thank you both for the clarification.

As a suggestion, it could be useful to include such an example in the usage tutorial, as std::cout'ing numbers will seem to "just work". I'm glad @gregmarr explained about the type that actually gets passed to cout (possibly what I was overlooking?).

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

int main(int argc, char *argv[])
{
    json j = R"({"one": "value", "two": 1.2345})"_json;

    std::cout << j["one"] << '\n';
    std::cout << j["one"].get<std::string>() << '\n';
    std::cout << j["two"] << '\n';
}

Output:

"value"
value
1.2345

I added a clarification in the README file.

Was this page helpful?
0 / 5 - 0 ratings