Home >Web Front-end >JS Tutorial >Simple and efficient JSON

Simple and efficient JSON

php中世界最好的语言
php中世界最好的语言Original
2018-03-16 17:31:281719browse

This time I bring you simple and efficient JSON. What are the precautions when using simple and efficient JSON? Here are practical cases, let’s take a look.

JSON (JavaScript Object Notation) is a text-based data exchange format. No matter which 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 of your favorite programming languages ​​​​to process JSON data. On the other hand, with the widespread use of REST and NoSQL technologies or standards like MongoDB, JSON is becoming a recommended data interaction format.

JSON was created by Douglas Crockford in 2001 and is defined as the RFC 4627 standard by the IETF (Internet Engineering Task Force). 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, which has three data structures:

Key-value pair——Name/Value (Key/Value)

Object——Object

Array——Arrays

A valid JSON document needs to be contained within 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, and the two have the same meaning.

Why use JSON

JSON is considered a good replacement for XML. Because JSON is very readable and does not contain many redundant element tags like XML, this makes applications that use JSON for network transmission and parsing faster and more efficient.

Key-value pair——Name/Value

The key-value pair is the most basic data structure in JSON:

{
  “firstName”: “John”
}

In the above example, the attribute "firstName" is used A string enclosed in double quotes. And its value "John" is also a string in this example. Of course, it can also be other types. For details, please refer to the following chapter Data Type. 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 unsorted 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 separated by .

Array - Array

[] in JSON to contain array elements, refer to the following example:

{
    “people” : [
        { “firstName”: “John”, “lastName”: “Smith”, “age”: 35 },
        { “firstName”: “Jane”, “lastName”: “Smith”, “age”: 32 }
    ]
}

Data type

Value in JSON ( The value in the key-value pair) can be any of the following:

Object, Array, String, Number, Boolean, ull, Number

Numeric typeThe data can be Integers can also be 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 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 before the value or use hexadecimal to represent a value.

Boolean

Boolean values ​​in JSON can be represented by true or false.

{
    “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 ' ' represents an empty string, and null represents a null value.

{
    “age” : null}

Code Comments

JSON does not allow comments to be added to JSON documents or strings. The annotation function first existed in JSON, but developers mistakenly used it to assist in parsing JSON data. When Douglas Crockford realized this bad usage practice, he canceled the annotation function to ensure that JSON Characteristics as an interactive data format between different computing platforms.

Style

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

Grammar

Douglas Crockford gives an explanation of all JSON syntax and semantics in 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 Verification

一个文本文档或字符串必须遵守JSON的语法定义,才能被视作一个有效的JSON文档。JSON文档是否有效非常重要,因为它直接决定了,你的JSON数据能否在不同的应用中被正确地解析和使用。JSONLint提供了一个可交互的Web版JSON校验工具,你只需要将你的JSON文档粘贴进去,并点击校验按钮,它便会自动进行校验,并将问题显示在下方。


在上面这个例子中,这个JSON对象的city属性没有加上双引号,导致校验失败。在返回的提示中,显示了“Expecting 'STRING', got 'undefined'”错误。

JSONLint也提供了一个可以在Chrome中直接使用的插件。

JSON数据模型

在应用中手工编写JSON文档,会很枯燥并容易出错。为了防止这样的恶错误 ,你可以使用JSONPad或JSON Editor Online这样的工具,它们能够帮助你构建JSON逻辑模型(类似于UML),然后通过模型生成JSON文档。

JSON Editor Online

[ JSON Editor Online] (http://jsoneditoronline.org/) 是一个在线JSON数据建模工具,他也提供了一个Chrome插件可以使用。


浏览器中的JSON

Firefox和Chrome都提供了一些很好的插件方便开发人员查看或处理JSON数据。

REST Client

Rest Client是Firefox中的一个扩展应用。他能够帮助开发人员在浏览器中调试REST风格的Web Service。它最大的优点是能将返回的JSON数据结果,以很好的格式显示出来。


JSONView

JSONView是一个FireFox和Chrome上的插件,能够很好地将JSON数据打印出来,从而大大提高了JSON数据的可读性。


JSON与AJAX

AJAX可能是使用JSON数据中最常见的场景了。下面的这段代码示例,通过jQuery来调用一个REST风格的Web Service,并处理返回的JSON对象。

$.getJSON(‘http://example/service/addresses/home/1’,
    function(data) {        var address = JSON.parse(data);        console.log(“Address Line 1 = “ + address.line1);
    }
);

在上面的这段代码中,$getJSON(这是一种jQuery中$.ajax()标准调用的一种缩写形式)会发起一个HTTP GET 请求,调用Web Service,之后在它的隐式回调函数中,获取返回的data数据,并通过JSON.parse()方法将返回的数据转换为JSON对象。之后便可以像获取普通属性那样(address.line1)获取对象的属性数值了。

JSON与JAVA

Jackson是JAVA中用来处理JSON的一个第三方库。它很有名,并且提供了一组非常好用的JSON API。下面就是它的一个例子:

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);

除了Jackson之外,还有一些其他基于JAVA的第三方JSON API库。

JSON与RUBY

Ruby中也有很多与JSON相关的第三方库,而JSON gem是Ruby自带的,下面就是它的用法:

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])] }]    endend

JSON gem的to_json方法将字符串或哈希转换为JSON。Address对象的to_json方法通过将它的成员转换成哈希再对哈希值调用to_json,最终将一个Address对象转换为JSON格式。

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”}

JSON gem的JSON.pase方法则将JSON字符串转换为哈希。Address对象的from_jason!方法接收一个JSON字符串,然后调用JSON.parse来转换哈希,然后再在对象上分别设置这些哈希的值。

json_addr = <<END
{
    “line1” : “999 Broadway”, “city” : “Anytown”,
    “state_or_province” : “CA”, “zip_or_postal_code” : “90210”,
    “country” : “USA”
}
END
addr2 = Address.newaddr2.from_json!(json_addr)

除了JSON gem之外,还有以下一些Ruby的JSON第三方库

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与RUBY ON RAILS

Ruby on Rails也提供了将Ruby对象转换为JSON的功能。下面的例子中的Controller使用了render方法将一个Ruby对象以JSON数据的格式进行输出。

Rails中的ApplicationController会负责对象与JSON数据之间的互相转换 。因此,不需要额外调用to_json方法。

JSON SCHEMA

JSON Schema用来定义JSON文档的结构,它可以被用来验证和校验发送或收到的JSON文档是否有效和规范。JSON Schema本身也是用JSON格式编写的,它的具体定义可以参考http://json-schema.org。

下面是JSON Schema的部分结构定义:

结构             描述

type              对象的数据类型,如Object,array,string,number 等    

$schema      提供Schema版本的URI    

required       true/false    

id                  数据元素id    

properties    数据元素的校验属性,包括最大值,最小值,枚举等    

下面是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
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

在上面的Schema中对JSON对象做了以下约束:

registrants必须是一个数组对象

phoneNumber的channel必须是cell, work, fax, home中的一个

address的premise必须是home, work, other中的一个。

一个使用上述JSON Schema的Web Service可以解析和处理下面这个JSON文档:

{    "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 生成器

我们可以使用JSON Schema生成器来为一个有效的JSON文档生成对应的Schema。你需要访问(www.jsonschema.net),然后按照以下步骤操作:

将你的JSON文档粘贴到右侧文本框

选择JSON输入选项

点击Generate Schema按钮

JSON Schema 校验器

我们可以用JSON Schema Validator来保证我们的JSON文档时有效的。下面是针对不同开发语言的一些常见的JSON Schema 校验器。

校验器

编程语言

项目地址

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

除了上面这些与编程语言相关的校验器之外,你还可以直接使用在线的JSON Schema校验器( http://json-schema-validator.herokuapp.com ),将Schema和JSON文档粘贴到左侧的文本框中,然后点击Validate按钮,校验的结果就会显示在屏幕右侧。

总结

以上,我们已经初步了解了JSON的核心定义和用法,但对于JSON本身来说我们还只是了解了其中很小的一部分,还有许多与它相关的工具或技术可以使用。JSON作为一个数据标准,它已经逐步替代XML成为Internet上最受欢迎的交互数据格式。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

全局计数的JavaScript代码

 判断相应式布局中当前适配度的JavaScript代码

限制文本字数的JavaScript代码

The above is the detailed content of Simple and efficient JSON. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn