How to install and use JsonCpp library on Ubuntu Linux OS?

Learn to configure, compile and run C++ programs using JsonCpp Library

Posted by Amritpal Singh on October 09, 2017

About JsonCpp

JsonCpp is a lightweight data-interchange format. It can represent numbers, strings, ordered sequences of values, and collections of name/value pairs.

Step 1: Install using apt-get

You can easily install JsonCpp library on Ubuntu or another flavor of Debian Linux simply by running the following command:

sudo apt-get install libjsoncpp-dev

It will install the compatible JsonCpp library on your system.

Step 2: Example program and compiler flag

To compile a C++ program that uses JsonCpp library use the compiler flag:

-ljsoncpp

Create a Json file called profile.json with the following content:

{
    "firstname":"Amritpal",
    "lastname": "Singh",
    "ss": 12345678910
}

Within the same directory create a profile.cpp file with the following source code:

#include <iostream>
#include <fstream>
#include <jsoncpp/json/json.h>

using namespace std;

int main() {
    ifstream ifs("profile.json");
    Json::Reader reader;
    Json::Value obj;
    reader.parse(ifs, obj);     // Reader can also read strings
    cout << "Last name: " << obj["lastname"].asString() << endl;
    cout << "First name: " << obj["firstname"].asString() << endl;
    return 1;
}

Compile it:

g++ -o profile profile.cpp -ljsoncpp

Run it:

./profile

That's it, if you can run the profile program you have successfully configured JsonCpp library.


12 Comments

Jimmy

Nice post. Helped me get started with JSON data in c++.

siva

Nice Post. will this Repo install the latest version of Jsoncpp.?? Can you please share some tutorial links that using JsonCpp. if you have Thanks siva

Aurora

Thank you very much for your post. I wish I'd seen it sooner it would have saved me quite a lot of time.

Peter Bums

2 + 3 = 5

iceCool Boi

Getting that fresh cream YYEEEAAHHHH BBBAAABBBYYYY

Jimmy

What heck are you doing?! write good comments not that nonsense

iceCool Boi

SHUT UP NOOOOB

Peter Bums

UUUHHHHH BEEEEEEEFFF

iceCool Boi

oh you are in a trouble boi

iceCool Boiy

But thanks for that nice advice my dawg Amritpal TH3NX for ya time, appreciate it. YO BOCCRLINX LINUX GANG BOI

alberto

Why is this so trivial by command line and so complicated in Eclipse?! It is not able to link objects in any way. It seems to not find the shared ljsoncpp library

saichand

Very straightforward. Nicely explained. Thank you.

Add Comment