Introduction to JSON

Source: Internet
Author: User
Tags ruby on rails json schema generator jsonlint
JSON overview
JSON (JavaScript Object Notation) is a text-based data exchange format. No matter what development language your application is written in (Java / EE, Ruby, PHP, C # /. Net, etc.), you can use JSON to interact and process data over the network. Almost all programming languages have good libraries or third-party tools to provide JSON-based API support, so you can easily use any programming language you like to process JSON data. On the other hand, with the widespread use of REST, NoSQL technologies or standards like MongoDB, JSON is also becoming a recommended data interaction format.

JSON was created by Douglas Crockford in 2001 and defined by IETF (Internet Engineering Task Force) as RFC 4627 standard. For details, please refer to: http://tools.ietf.org/html/rfc4627 The media type of JSON is defined as application / json, and the file suffix is .json.

What is JSON
JSON is a simple data format, it has three data structures:

Key-value pairs-Name / Value (Key / Value)
Object-Object
Arrays-Arrays
A valid JSON document needs to be enclosed in a pair of curly braces
{JSON-Data}

Please note that some development communities or online documents directly refer to the above JSON document as a JSON string, which means the same thing.

Why use JSON
JSON is considered a good alternative to XML. Because the readability of JSON is very good, and it does not contain many redundant element tags like XML, this makes the application use JSON for network transmission and parsing processing faster and more efficiently.

Key-value pair-Name / Value
Key-value pairs are the most basic data structure in JSON:
{“FirstName”: “John”}

In the above example, the attribute "firstName" is a string enclosed in double quotes. The value of "John" is also a string in this example. Of course, it can also be other types. For details, please refer to the chapter on data types. Many products or technologies on the market claim that they use the JSON data format, but when they define attributes, they do not enclose the attribute names in double quotes. In fact, this violates the JSON definition standard.

Object-Object
A JSON object is a collection of unordered key-value pairs. The address in the following example is a JSON object:

{
    "Address": {
        "Line1": "555 Main Street",
        "City": "Denver",
        "StateOrProvince": "CO",
        "ZipOrPostalCode": "80202",
        "Country": "USA"
    }
}
In the above example, the address object contains 5 attributes, which are used to divide.

Array-Array
JSON [] contains array elements, refer to the following example:

{
    "People": [
        {“FirstName”: “John”, “lastName”: “Smith”, “age”: 35},
        {“FirstName”: “Jane”, “lastName”: “Smith”, “age”: 32}
    ]
}
type of data
The value in JSON (the value in the key-value pair) can be any of the following:
Object
Array
String
Number
Boolean
null

Number
Numeric data can be integer or double-precision floating-point data. Here are some examples:
"Age": 29 "cost": 299.99 "temperature": -10.5 "speed_of_light": 1.23e11 "speed_of_light": 1.23e + 11 "speed_of_light": 1.23E11 "speed_of_light": 1.23E + 11

The above attributes (such as age, etc.) are all strings enclosed in double quotes, and the values do not need to be enclosed in double quotes. You can add a-sign before the value to indicate negative numbers, or you can use scientific notation. But you cannot add 0 in front of the value or use hexadecimal to represent a value.

Boolean
The Boolean value in JSON can be expressed as true or false. Don't add {}
{“EmailValidated”: true}
Boolean values do not need to be modified with double quotes.

null
Strictly speaking, null is not a data type, but it is very important, it means that an attribute or element has no value. So please note that ‘’ means an empty string, and null means an empty value.
{“Age”: null}

Code comments
JSON does not allow comments to be added to JSON documents or strings. The comment function first existed in JSON, but developers used it incorrectly to assist in the analysis of JSON data. When Douglas Crockford realized this bad usage practice, he canceled the comment function to ensure that JSON is in The characteristics of the interactive data format between different computing platforms.

style
You may have noticed that in the previous example, all attribute names used camel-case naming rules. This is not a standard requirement of JSON, but it can help improve the readability of JSON documents, so it is used as a de facto standard in all JSON applications.

grammar
Douglas Crockford gives a description of all JSON syntax and semantics on his JSON website http://www.json.org/. There is also an iOS App JSON Pro FREE that can be used to learn or refer to JSON through examples.

JSON validation
A text document or string must comply with the JSON grammar definition in order to be considered a valid JSON document. Whether the JSON document is valid is very important, because it directly determines whether your JSON data can be correctly parsed and used in different applications. JSONLint provides an interactive web version JSON verification tool. You only need to paste your JSON document and click the verification button, it will automatically verify and display the problem below.


Paste_Image.png
In the above example, the city property of this JSON object was not enclosed in double quotes, which caused the verification to fail. In the returned prompt, the error "Expecting‘ STRING ’, got‘ undefined ’was displayed.
JSONLint also provides a plugin that can be used directly in Chrome.

JSON data model
Manually writing JSON documents in an application can be tedious and error-prone. In order to prevent such evil errors, you can use tools such as JSONPad or JSON Editor Online, which can help you build a JSON logical model (similar to UML), and then generate JSON documents through the model.

JSON Editor Online
[JSON Editor Online] (http://jsoneditoronline.org/) is an online JSON data modeling tool, he also provides a Chrome plugin to use.


Paste_Image.png JSON in the browser
Both Firefox and Chrome provide some good plug-ins for developers to view or process JSON data.

REST Client
Rest Client is an extension application in Firefox. He can help developers debug REST-style Web Services in the browser. Its biggest advantage is that it can display the returned JSON data results in a very good format.


Paste_Image.png JSONView
JSONView is a plug-in on FireFox and Chrome that can print out JSON data very well, thus greatly improving the readability of JSON data.


Paste_Image.png JSON and AJAX
AJAX is probably the most common scenario when using JSON data. The following code example uses jQuery to call a REST-style Web Service and process the returned JSON object.

$ .getJSON (‘http: // example / service / addresses / home / 1’,
    function (data) {
        var address = JSON.parse (data);
        console.log ("Address Line 1 =" + address.line1);
    }
);
In the above code, $ getJSON (this is a short form of the standard call of $ .ajax () in jQuery) will initiate an HTTP GET request, call the Web Service, and then in its implicit callback function , Get the returned data, and convert the returned data to a JSON object through the JSON.parse () method. After that, you can get the attribute value of the object like the normal attribute (address.line1).

JSON and JAVA
Jackson is a third-party library used to process JSON in JAVA. It is very famous, and provides a set of very easy to use JSON API. Here is an example of it:

import java.io.Writer;
import java.io.StringWriter;
import org.codehaus.jackson.map.ObjectMapper;

public class Address {
    private String line1;
    private String city;
    private String stateOrProvince;
    private String zipOrPostalCode;
    private String country;

    public Address () {}

    public String getLine1 () {
        return line1;
    }

    public void setLine1 (line1) {
        this.line1 = line1;
    }

    // Remaining getters and setters ...
}

Address addrOut = new Address ();

// Call setters to populate addrOut…
ObjectMapper mapper = new ObjectMapper (); // Reuse this.
// Marshal Address object to JSON String.
Writer writer = new StringWriter ();
mapper.writeValue (writer, addrOut);
System.out.println (writer.toString ());

// Unmarshal Address object from JSON String.
String addrJsonStr =
"{" +
    "\" Address \ ": {" +
    “\” Line1 \ ”: \” 555 Main Street \ ”,” +
    "\" City \ ": \" Denver \ ","
    “\” StateOrProvince \ ”: \” CO \ ”,”
    "\" ZipOrPostalCode \ ": \” 80202 \ ”,” +
    “\” Country \ ”: \” USA \ ”” +
    "}" +
"}";

Address addrIn = mapper.readValue (addrJsonStr, Address.class);
In addition to Jackson, there are other third-party JSON API libraries based on JAVA.
API
Source

Google GSON
http://code.google.com/p/google-json/

SOJO
http://sojo.sourceforge.net/

org.json (by DouglasCrockford)
http://www.json.org/java

json-lib
http://sourceforge.net/projects/json-lib/

json-io
http://code.google.com/p/json-io

jsontools
http://jsontools.berlios.de/

jsonbeans
http://code.google.com/p/jsonbeans/

JSON and RUBY
There are also many third-party libraries related to JSON in Ruby, and the JSON gem comes with Ruby. The following is its usage:

require ‘json’
class Address
    attr_accessor: line1,: city,: state_or_province,
                  : zip_or_postal_code,: country

    def initialize (line1 = ’’, city = ’’, state_or_province = ’’,
        zip_or_postal_code = ’’, country = ’’)
        @ line1 = line1
        @city = city
        @state_or_province = state_or_province
        @zip_or_postal_code = zip_or_postal_code
        @country = country
    end

    def to_json
        to_hash.to_json
    end

    def from_json! (str)
        JSON.parse (str) .each {| var, val | send (“# {var} =”, val)}
    end

    private

    def to_hash
        Hash [instance_variables.map {| var | [var [1 ..- 1] .to_sym,
            send (var [1 ..- 1])]}]
    end
end
The to_json method of the JSON gem converts a string or hash to JSON. The to_json method of the Address object converts its members into hashes and then calls to_json on the hash value, and finally converts an Address object into JSON format.

addr1 = Address.new (‘555 Main Street’, ‘Denver’, ‘CO’, ‘80231’,
‘US’)
puts addr1.to_json
# Outputs the following…
{“Line1”: ”555 Main Street”, ”city”: ”Denver”, ”state_or_
province ”:” CO ”,” zip_or_postal_code ”:” 80231 ”,” country ”:” US ”}
The JSON.pase method of the JSON gem converts the JSON string to a hash. The from_jason! Method of the Address object receives a JSON string, then calls JSON.parse to convert the hash, and then sets these hash values on the object.
json_addr = << END {"line1": "999 Broadway", "city": "Anytown", "state_or_province": "CA", "zip_or_postal_code": "90210", "country": "USA"} ENDaddr2 = Address .newaddr2.from_json! (json_addr)

In addition to the JSON gem, there are the following Ruby JSON third-party libraries
API
Source

ActiveSupport JSON
http://api.rubyonrails.org/classes/ActiveSupport/JSON.html

Yajl
https://github.com/brianmario/yajl-ruby

Oj
https://github.com/ohler55/oj

JSON and RUBY ON RAILS
Ruby on Rails also provides the ability to convert Ruby objects to JSON. The Controller in the following example uses the render method to output a Ruby object as JSON data.
ApplicationController in Rails will be responsible for the conversion between objects and JSON data. Therefore, no additional to_json method needs to be called.

JSON SCHEMA
JSON Schema is used to define the structure of JSON documents. It can be used to verify and verify whether the JSON documents sent or received are valid and standardized. JSON Schema itself is also written in JSON format, and its specific definition can refer to http://json-schema.org.
The following is a partial structure definition of JSON Schema:
structure
description

type
The data type of the object, such as Object, array, string, number, etc.

$ schema
Provide Schema version of URI

required
true / false

id
Data element id

properties
Data element verification attributes, including maximum, minimum, enumeration, etc.

Here is an example of JSON Schema
"Type": "object", "$ schema": "http://json-schema.org/draft-03/schema", "id": "#", "required": true, "properties": { “Registrants”: {“type”: “array”, “id”: “registrants”, “required”: true, “items”: {“type”: “object”, “required”: false, “properties”: {“Address”: {“type”: “object”, “id”: “address”, “required”: true, “properties”: {“city”: {“type”: “string”, “id”: “City”, “required”: true}, “country”: {“type”: “string”, “id”: “country”, “required”: false}, “line1”: {“type”: “string ”,“ Id ”:“ line1 ”,“ required ”: true},“ line2 ”: {“ type ”:“ string ”,“ id ”:“ line2 ”,“ required ”: false},“ postalCode ”: { “Type”: “string”, “id”: “postalCode”, “required”: true}, “premise”: {“type”: “string”, “id”: “premise”, “required”: true, "Enum": ["work ”,“ Home ”,“ other ”]},“ stateOrProvince ”: {“ type ”:“ string ”,“ id ”:“ stateOrProvince ”,“ required ”: true}}},“ firstName ”: {“ type ” : “String”, “id”: “firstName”, “required”: true}, “lastName”: {“type”: “string”, “id”: “lastName”, “required”: true}, “phoneNumber ”: {“ Type ”:“ object ”,“ id ”:“ phoneNumber ”,“ required ”: true,“ properties ”: {“ channel ”: {“ type ”:“ string ”,“ id ”:“ channel ” , “Required”: true, “enum”: [“cell”, “work”, “home”]}, “number”: {“type”: “string”, “id”: “number”, “required” : true}}}}}}}}}

The following constraints are imposed on the JSON object in the above Schema:
registrants must be an array object
phoneNumber channel must be one of cell, work, fax, home
The promise of address must be one of home, work, other.

A Web Service using the above JSON Schema can parse and process the following JSON document:
{"registrants": [{"firstName": "Fred", "lastName": "Smith", "phoneNumber": {"channel": "cell", "number": "303-555-1212"}, " address ": {" premise ":" home "," line1 ":" 555 Broadway NW "," line2 ":" # 000 "," city ":" Denver "," stateOrProvince ":" CO "," postalCode " : "88888", "country": "USA"}}]}

JSON Schema generator
We can use the JSON Schema generator to generate the corresponding Schema for a valid JSON document. You need to visit (www.jsonschema.net) and then follow these steps:
Paste your JSON document into the right text box
Choose JSON input options
Click the Generate Schema button

JSON Schema validator
We can use JSON Schema Validator to ensure that our JSON document is valid. The following are some common JSON Schema validators for different development languages.
Checker
Programming language
project address

JSV
JavaScript
https://github.com/garycourt/JSV

Ruby JSON Schema Validator
Ruby
https://github.com/hoxworth/jsonschema

json-schemavalidator
Java
https://github.com/fge/json-schema-validator

php-json-schema (by MIT)
PHP
https://github.com/hasbridge/php-json-schema

JSON.Net
.NET
http://james.newtonking.com/projects/json-net.aspx

In addition to the above validators related to programming languages, you can also directly use the online JSON Schema validator (http://json-schema-validator.herokuapp.com) to paste the Schema and JSON documents to the left Click the Validate button in the text box on the side, and the verification result will be displayed on the right side of the screen.
to sum up
Above, we have initially understood the core definition and usage of JSON, but for JSON itself we have only understood a small part of it, and there are many tools or technologies related to it that can be used. As a data standard, JSON has gradually replaced XML as the most popular interactive data format on the Internet.
Bookmark about artisans, welcome to share the above content to the circle of friends / Weibo, etc. If you need to reprint, please contact the authorized by short letter. thank you all!





About Json

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.