Json: How to save json to file?

Created on 10 Aug 2017  Â·  12Comments  Â·  Source: nlohmann/json

I'm trying to save json to file and all I'm getting is some weird errors. Any help?
Here is all the info:

Verison json: 2.1.1

gcc version 6.3.0 20170618 (Ubuntu 6.3.0-19ubuntu1)

Example code

#include "json.hpp"
using jsonf = nlohmann::json;
jsonf jsonfile;

// ...

jsonfile["foo"] = "bar";

std::fstream file("key.json");
file << jsonfile;

Error

json.hpp:843:9: error: static assertion failed: could not find to_json() method in T's namespace
         static_assert(sizeof(BasicJsonType) == 0,
         ^~~~~~~~~~~~~

json.hpp:843:9: error: static assertion failed: could not find to_json() method in T's namespace

Most helpful comment

This code works for me:

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

using jsonf = nlohmann::json;

int main() {
    jsonf jsonfile;

    jsonfile["foo"] = "bar";

    std::ofstream file("key.json");
    file << jsonfile;
}

All 12 comments

This code works for me:

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

using jsonf = nlohmann::json;

int main() {
    jsonf jsonfile;

    jsonfile["foo"] = "bar";

    std::ofstream file("key.json");
    file << jsonfile;
}

Sorry, replace:
jsonfile["foo"] = "bar";
with

const unsigned char a[] = "testing";
jsonfile["foo"] = a;

This works for me with the latest version of the develop branch and GCC 6.4.0 (macOS)

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

using jsonf = nlohmann::json;

int main() {
    jsonf jsonfile;

    const unsigned char a[] = "testing";
    jsonfile["foo"] = a;

    std::ofstream file("key.json");
    file << jsonfile;
}

Note the output is

{"foo":[116,101,115,116,105,110,103,0]}

Use const char a[] = "testing"; if you want the content to be interpreted as characters rather than numbers.

Strange... I will see what can I do.

Are you using the latest release? If so, it is likely that this is fixed on develop

I guess thats fixed somehow, but now i get this error:

 error: cannot convert ‘nlohmann::basic_json<>::value_type {aka nlohmann::basic_json<>}’ to ‘const unsigned char*’ in initialization
     const unsigned char * key = jsonfilekey["key"];

String are stored as std::string inside the JSON value. You can write

std::string key = jsonfilekey["key"];

and organize the conversion to const unsigned char* from there.

Related: #683

For unknown reasons, that corrupts the whole string.
My string contains of base64(raw bytes).

What do you mean with "corrupts". Can you provide an example?

Any news on this?

@NeverMine17 Any news on this?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

past-due picture past-due  Â·  4Comments

SimplyLiz picture SimplyLiz  Â·  3Comments

sqwunkly picture sqwunkly  Â·  3Comments

bassosimone picture bassosimone  Â·  3Comments

jmlemetayer picture jmlemetayer  Â·  3Comments