Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying The JavaScript JSON Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
The JavaScript JSON Cookbook

The JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie
1 (2)
close
close
The JavaScript JSON Cookbook

The JavaScript JSON Cookbook

1 (2)
By: Ray Rischpater, Brian Ritchie

Overview of this book

If you're writing applications that move structured data from one place to another, this book is for you. This is especially true if you've been using XML to do the job because it's entirely possible that you could do much of the same work with less code and less data overhead in JSON. While the book's chapters make some distinction between the client and server sides of an application, it doesn't matter if you're a frontend, backend, or full-stack developer. The principles behind using JSON apply to both the client and the server, and in fact, developers who understand both sides of the equation generally craft the best applications.
Table of Contents (12 chapters)
close
close
11
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/.

Create a Note

Modal Close icon
You need to login to use this feature.
notes
bookmark search playlist font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY