Reading JSON

Using REST is tough enough but now you will have to read JSON. But that's no problem really.

By Robert Delwood

A Lead API Documentation Writer

[Home] [Writing samples] [LinkedIn]

Download Text File

Introduction

REST programming is all about JSON. JSON is an established, well-documented, structured data format that allows exchanging data over the Internet. It’s used extensively in both directions, when data is sent to servers, and when it’s returned from servers. REST application use it for most response requests, or returning data from a server. In brief, JSON is data in pairings, like a dictionary entry.

The simplest example is:

	"name": "Robert" 

The left side of the colon is called the key, and is the name of the entry, here as name. The right side is the value, Robert.

Structures can get exceedingly complex and long, but all entries are ultimately still a pairing. It’s usually the value that is programmers are looking for. This tutorial introduces the concepts and formats of JSON, and explains how to access individual pieces of information programmatically.

Setting Up the Examples

There are six examples that run in a progression, for simple JSON to complex objects. Microsoft Visual Studio and its debugger will be used to display the information.

To run these examples, you will need the following.

The example project already contains the Newtonsoft code but the library, or reference, has to be added to the project. To do that:

  1. Double click JSON_Viewer.sln to start Visual Studio and to open the project.
  2. Click Project > Manage NuGet. Browse for Newtonsoft.
  3. Select Newtonsoft.Json, and install.

By default, the sample project is set to open the file json_example_1.txt. Each example uses a different file. Change the file name, really nothing more than json_example_1.txt to json_example_2.txt, for example.

Parsing

Getting a value is called parsing.

JSON is returned from requests formatted but as plain text. To be more easily parsed, the JSON needs to be converted to another format. The Newtonsoft library introduces an object, called JObject, whose important element is essentially JSON in an array. Many users know accessing arrays through an index number, such as myArray[0]. For JObjects, the key is used instead, such as:

	jsonObject["name"] 

That means we can access fields directly, but notice that getting this information means you have to know something about the structure, mainly the key. In this simple case, you can either look at the source file, there is only one entry after all, or use Visual Studio’s debugger to watch the object.

Parsing JSON

The simplest JSON is :

Example 1

 {
 	"name": "Robert"
 } 

This has one entry, with the key being name and its value is Robert. To see this:

1. Set a breakpoint at line 27.

2. Run the application. By default, the sample project is set to open the file json_example_1.txt.

3. When the application breaks, enter as a new line the watch window:

	jsonObject["name"] 

4. The value Robert displays.

Example of the debugger display.

Example 2

There could be multiple entries:

 {
 	"name": "Robert", 
	"employee_number" : 148, 
	"is_active": true
 }

Now it has three entries, adding an employee number as an integer, and an active status of a Boolean. To see this:

1. Set a breakpoint at line 27.

2. Set to open the file in line 21 to json_example_2.txt, and run the application.

3. When the application breaks, enter each as a new line the watch window:

	jsonObject["name"]
	jsonObject["employee_number"]
	jsonObject["is_active"] 

4. The appropriate value displays.

Example 3

Arrays are allowed. Arrays are a set of items for a single entry. For example:

 { 
	"name": "Robert", 
	"employee_number" : 148, 
	"is_active": true, 
	"specialties": [ "Programming", "Writing", "Accounting" ] 
} 

The key specialties has a value that is an array, and that has three items. Like other arrays, each items can be accessed by an index.

1. Set a breakpoint at line 27.

2. Set to open the file in line 21 to json_example_3.txt, and run the application.

3. When the application breaks, enter as a new line the watch window:

	jsonObject["specialties"][0]

4. The value Programming displays. Display the other values by entering 1 and 2.

Example 4

The next kind of JSON entry is the object. An object is set of other named pairs within a single entry. For example:
{ 
	"name": "Robert", 
	"employee_number" : 148, 
	"is_active": true, 
	"specialties": [ "Programming", "Writing", "Accounting" ], 
	"personal": { "name":"Robert", "age":46, "city":"Chicago" } 
} 

The key personal is an object. The value is contained within parentheses that notes it as an object. That object itself is composed of three named pairs: name, age, and city. Each has a directly corresponding value of Robert, 46, and Chicago respectively.

Multiple objects are allowed. This example has two objects. The key personal is one object, but the JSON itself is an object.

1. Set a breakpoint at line 27.

2. Set to open the file in line 21 to json_example_4.txt, and run the application.

3. When the application breaks, enter as a new line the watch window:

	jsonObject["personal"]["city"]

4. The value Chicago displays. Display the other values by entering the other two keys.

Example 5

Remember, an object is anything within parentheses. In turn, objects themselves can contain objects. This example combines the JSON features to detail an employee. Building on the previous examples, address entry is added. This is an array of address objects. There two items in the array, and each address object contains keys for street, zip code, and state. Even though there are more entries, the process is still the same. If you know the structure, you can walk down the path.

1. Set a breakpoint at line 27.

2. Set to open the file json_example_5.txt, and run the application.

3. When the application breaks, enter as a new line the watch window:

	jsonObject["personal"]["address"][1]["street"] 

4. The value 1564 W. Melamn displays.

{
	"name": "Robert", 
	"employee_number" : 148, 
	"is_active": true, 
	"specialties": [ "Programming", "Writing", "Accounting" ], 
	"personal": 
	{ 
		"name":"John", "age":42, "city":"New York", "address" : 
			[ 
				{ "street": "100 Pearlman", "zip": 10001, "state":    "WA"}, 
				{ "street": "1564 W. Melamn", "zip": 60609, "state": "IL"} 
			] 
	}
}

Example 6

While object nesting complicates the readability, at least for human readability, it does create a useful flexibility. The previous example illustrates one employee. However, companies like to have more than one employee and this can be represented in JSON as an array of employee objects. The following has two entries at the root level. "total_employees" shows the number of employees that are included here, and an employees array noted by the square brackets as the value. Each employee object is enclosed in soft brackets and separated by commas. This example shows a common case that objects being repeated. A request, for example, listing company employees might return many employees, perhaps thousands, as an array of employee objects. To access any one, just include the index.

1. Set a breakpoint at line 27.

2. Set to open the file in line 21 to json_example_6.txt, and run the application.

3. When the application breaks, enter as a new line the watch window:

	jsonObject["employees"][1]["name"] 

4. The value Jennifer displays.

Schemas

For small examples, such as they are here, you can simply look at the JSON and figure it out. As demonstrated, you can also use the debugger to walk through the structure. But what if the JSON is more complex than that? There are on line JSON editors that you can copy and paste to. Some will “prettify” the code. This is an industry term that formats the structure in a systematic or more human readable form. Ultimately, there is the object schema. This is the definition of what’s allowed in the JSON. Many APIs require a schema for each JSON object type they use. It validates the JSON, either allowing it to be sent or not. This should be available through the API documentation or the project’s repository, like GitHub. The schema for example 1 would look like:

 {
	"$schema": "http://json-schema.org/draft-04/schema#", 
	"type": "object", 
	"properties": 
	{ 
		"name": { "type": "string" } 
	}, 
	"required": [ "count" ]
} 

The points of interest are the items under properties. There is one. It is called name and is a string.