c++jsonjson-spirit

Trying to write a JSON to a file using JSON Spirit in C++


I am trying to write to a JSON to a file using JSON Spirit.

I am using the code similar to the examples given on the website to do this as follows:

json_spirit::Object emotion_json;
emotion_obj.push_back(json_spirit::Pair("Dominant emotion", "Joy"));

ofstream os("emotion_json.json");
json_spirit::write(emotion_obj, os);
os.close();

I keep getting the error:

undefined reference to 'json_spirit::write(json_spirit::Value_impl<json_spirit::Config_vector<std::string> > const&, std::ostream&, int, unsigned int)'

I tried different variations witin JSON Spirit to output the JSON to a file, but none of them seem to be working for me despite having the headers:

#include <json_spirit.h>
#include <json_spirit_writer_template.h>
#include <json_spirit_writer.h>

Any idea what might be going on? Also, if there is a better, light-weight library to create JSON structures in C++, I am all ears. Thanks!


Solution

  • Turn on the linking option:

    -ljson_spirit
    

    If compiler cannot find json_spirit, use

    -L /path/to/the/parent/folder/of/libjson_spirit.a 
    

    before json_spirit and after the name of .cpp file.

    If you cannot find any libjson_spirit.a, you should build the library.

    Go to the folder json_spirit in the source code where you see file CMakeLists.txt.

    In the command line type:

    cmake .
    make
    

    Then libjson_spirit.a will be created.