Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The JavaScript JSON Cookbook

You're reading from   The JavaScript JSON Cookbook Over 80 recipes to make the most of JSON in your desktop, server, web, and mobile applications

Arrow left icon
Product type Paperback
Published in Jun 2015
Publisher
ISBN-13 9781785286902
Length 192 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Table of Contents (12) Chapters Close

Preface 1. Reading and Writing JSON on the Client FREE CHAPTER 2. Reading and Writing JSON on the Server 3. Using JSON in Simple AJAX Applications 4. Using JSON in AJAX Applications with jQuery and AngularJS 5. Using JSON with MongoDB 6. Using JSON with CouchDB 7. Using JSON in a Type-safe Manner 8. Using JSON for Binary Data Transfer 9. Querying JSON with JSONPath and LINQ 10. JSON on Mobile Platforms Index

Reading and writing JSON in C++

C++ is a language that long-predates JSON, but is still relevant for many projects. There's no native support for JSON in C++ but there are a number of libraries that provide support for working with JSON. Perhaps the most widely used is JsonCpp, available from GitHub at https://github.com/open-source-parsers/jsoncpp. It's licensed under the MIT license or public domain if you so desire, so there are virtually no limitations on its use.

Getting ready

To use JsonCpp, you need to first go to the website and download the zip file with the entire library. Once you do so, you need to integrate it with your application's source code.

How you integrate it with your application's source code differs from platform to platform, but the general process is this:

  1. Create an amalgamated source and header for the library using the instructions on the website. To do this, you'll need to have JsonCpp downloaded and Python 2.6 or later installed. From the top level directory of JsonCpp, run python amalgamate.py.
  2. Include the include file dist/json/json.h in any file where you want to use the JsonCpp library.
  3. Include the source file dist/jsoncpp.cpp in your project's make file or build system.

Once you do this, you should have access to the JsonCpp interface in any file that includes the json/json.h header.

How to do it...

Here's a simple C++ application that uses JsonCpp to convert between std::string containing some simple JSON and a JSON object:

#include <string>
#include <iostream>
#include "json/json.h"

using namespace std;

int main(int argc, _TCHAR* argv[])
{
  Json::Reader reader;
  Json::Value root;

  string json = "{\"call\": \"KF6GPE\",\"type\":\"l\",\"time\":
  \"1399371514\",\"lasttime\":\"1418597513\",\"lat\": 37.17667,
  \"lng\": -122.14650,\"result\":\"ok\"}";

  bool parseSuccess = reader.parse(json, root, false);

  if (parseSuccess)
  {
    const Json::Value resultValue = root["result"];
    cout << "Result is " << resultValue.asString() << "\n";
  }

  Json::StyledWriter styledWriter;
  Json::FastWriter fastWriter;
  Json::Value newValue;
  newValue["result"] = "ok";

  cout << styledWriter.write(newValue) << "\n";
  cout << fastWriter.write(newValue) << "\n";

  return 0;
}

How it works...

This example begins by including the necessary includes, including json/json.h, which defines the interface to JsonCpp. We explicitly reference the std namespace for brevity, although don't do so for the Json namespace, in which JsonCpp defines all of its interfaces.

The JsonCpp implementation defines Json::Reader and Json::Writer, specifying the interfaces to JSON readers and writers, respectively. In practice, the Json::Reader interface is also the implementation of a JSON class that can read JSON, returning its values as Json::Value. The Json::Writer variable just defines an interface; you'll want to use a subclass of it such as Json::FastWriter or Json::StyledWriter to create JSON from Json::Value objects.

The previous listing begins by defining Json::Reader and Json::Value; we'll use the reader to read the JSON we define on the next line and store its value in the Json::Value variable root. (Presumably your C++ application would get its JSON from another source, such as a web service or local file.)

Parsing JSON is as simple as calling the reader's parse function, passing the JSON and Json::Value into which it will write the JSON values. It returns a Boolean, which will be true if the JSON parsing succeeds.

The Json::Value class represents the JSON object as a tree; individual values are referenced by the attribute name in the original JSON, and the values are the values of those keys, accessible through methods such as asString, which returns the value of the object as a native C++ type. These methods of Json::Value includes the following:

  • asString, which returns std::string
  • asInt, which returns Int
  • asUInt, which returns UInt
  • asInt64, which returns Int64
  • asFloat, which returns float
  • asDouble, which returns double
  • asBool, which returns bool

In addition, the class provides operator[], letting you access array elements.

You can also query a Json::Value object to determine its type using one of these methods:

  • isNull, which returns true if the value is null
  • isBool, which returns true if the value is bool
  • isInt, which returns true if the value is Int
  • isUInt, which returns true if the value is UInt
  • isIntegral, which returns true if the value is an integer
  • isDouble, which returns true if the value is double
  • isNumeric, which returns true if the value is numeric
  • isString, which returns true if the value is a string
  • isArray, which returns true if the value is an array
  • isObject, which returns true if the value is another JSON object (which you can decompose using another Json::Value value)

At any rate, our code uses asString to fetch the std::string value encoded as the result attribute, and writes it to the console.

The code then defines Json::StyledWriter and Json::FastWriter to create some pretty-printed JSON and unformatted JSON in strings, as well as a single Json::Value object to contain our new JSON. Assigning content to the JSON value is simple because it overrides the operator[] and operator[]= methods with the appropriate implementations to convert standard C++ types to JSON objects. So, the following line of code creates a single JSON attribute/value pair with the attribute set to result, and the value set to ok (although this code doesn't show it, you can create trees of JSON attribute-value pairs by assigning JSON objects to other JSON objects):

newValue["result"] = "ok";

We first use StyledWriter and then FastWriter to encode the JSON value in newValue, writing each string to the console.

Of course, you can also pass single values to JsonCpp; there's no reason why you can't execute the following code if all you wanted to do was pass a double-precision number:

Json::Reader reader;
Json::Value piValue;

string json = "3.1415";
bool parseSuccess = reader.parse(json, piValue, false);
  double pi = piValue.asDouble();

See also

For the documentation for JsonCpp, you can install doxygen from http://www.stack.nl/~dimitri/doxygen/ and run it over the doc folder of the main JsonCpp distribution.

There are other JSON conversion implementations for C++, too. For a complete list, see the list at http://json.org/.

You have been reading a chapter from
The JavaScript JSON Cookbook
Published in: Jun 2015
Publisher:
ISBN-13: 9781785286902
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime