JSON

JSON的数据结构

JSON中可以使用的数据类型

在线查看JSON中定义的数据

JSON格式校验

JSON与Javascript进行组合

使用JSON Path查询特定数据

使用JSONP完成跨域访问

JSON的变体-MongoDB中存储数据所用的BSON

 

JSON is a lightweight text-based open standard data-interchange format. It is human readable. JSON is derived from a subset of JavaScript programming language (Standard ECMA-262 3rd Edition—December 1999). It is entirely language independent and can be used with most of the modern programming languages.

JSON是一个轻量级的基于文本的标准数据交换格式。可读性极佳。

JSON源于javascript编程语言的一个子集所发展而来。

它不依赖于任何语言的开发环境,并且被大多数现代编程语言所支持的。

 

JSON is often used to serialize and transfer data over a network connection, for example between web server and a web application. In computer science, serialization is a process to transforming data structures and objects in a format suitable to be stored in a file or memory buffer or transmitted over a network connection. Later on, this data can be retrieved. Because of the very nature of the JSON, it is useful for storing or representing semi structured data.

JSON通常被用来在网络上通过序列化完成传输功能。

在计算机科学中,序列化指的是转换数据结构和使用合适的格式将对象存储到文件或者内存缓冲区或者在网络上传输。

以后,该数据能够被还原。因为JSON所采用的完全自然的表达方式,使其有利于保存或重现结构化的数据。

 

 

JSON files are saved with .json extension. Internet media type of JSON is "application/json".

JSON扩展名: .json

MIME类型:application/json

 

JSON的组成:

key:字符串

value:

基本类型:字符串("Kidle Edition")、数字(1.20)、布尔值(true/false)、null

结构化数据类型:对象({ })、数组([ ])

 

JSON
 

 

 

=======================================================================

 

JSON uses Object and Array as data structures and strings, number, true, false and null as vales. Objects and arrays can be nested recursively. - See more at: http://www.w3resource.com/JSON/introduction.php#sthash.AtGiLMQ5.dpuf

JSON uses Object and Array as data structures and strings, number, true, false and null as vales.

Objects and arrays can be nested recursively

对象与数组嵌套完成数据定义

 

{
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "address": {
        "streetAddress": "144 J B Hazra Road",
        "city": "Burdwan",
        "state": "Paschimbanga",
        "postalCode": "713102"
    },
    "phoneNumber": [
        {
            "type": "personal",
            "number": "09832209761"
        },
        {
            "type": "fax",
            "number": "91-342-2567692"
        }
    ]
}

 

JSON中合法的Value

String || Number || Object || Array || TRUE || FALSE || NULL
A value can be a string, a number, an object, an Array, a Boolean value (i.e. true or false) or Null. This structure can be nested.
字符串 || 数字 || 对象 || 数组 || TRUE || FALSE || NULL

对象与数组可以嵌套

 

在线查看/格式化JSON中定义的数据

http://jsoneditoronline.org/

http://jsonviewer.stack.hu/

http://chris.photobooks.com/json/default.htm

 

JSON格式正确性校验

http://jsonlint.com/

http://www.bejson.com

 

JSON与Javascript进行组合

What is serialize and deserialize

Get JSON value from JavaScript value is serialization and when it's other way (JSON to JavaScript) is deserialization. serialization: 将javascript中的对象转换为JSONdeserialization: 将JSON转换为javascript中的对象

 

JavaScript JSON object

The JavaScript JSON object comprises methods using which you can convert JavaScript values to JSON format and JSON notation to JavaScript values.

Javascript中的JSON对象包含这样的方法:

JSON.stringify:将Javascript中定义的变量转换为JSON格式的数据

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON.stringify</title>
</head>
<body>
	<script type="text/javascript">
		var w3r = {};
		w3r.name = "w3resource";
		w3r.ip = "201.2.31.82";
		//将javascript对象转换为json数据
		var jsonStr = JSON.stringify(w3r);
		document.write(typeof jsonStr);
		document.write(": ");
		document.write(jsonStr);
		
		//output:
		//string:{"name":"w3resource","ip":"201.2.31.82"} 
	</script>
</body>
</html>

 

JSON.parse:将JSON格式的数据转换为Javascript中的对象

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON.stringify</title>
</head>
<body>
	<script type="text/javascript">
		var jsonStr = '{"name":"w3resource","ip":"201.2.31.82"}';
		var converToObj = JSON.parse(jsonStr);
		document.write("name=");
		document.write(converToObj.name);
		document.write(", ip=");
		document.write(converToObj.ip);
		//output:
		//name=w3resource, ip=201.2.31.82 
	</script>
</body>
</html>

 

 

使用JSON Path查询特定数据

要使用jsonPath进行查找,需要引入2个额外的js:json.js, jsonpath.js (见附件)

jsonPath(obj, expr [, args])

obj: 由json转换得到的对象

expr:查询字符串(http://goessner.net/articles/JsonPath/)

[,args]: 暂时不学

 

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    }
}

 

XPath JSONPath Result
/store/book/author $.store.book[*].author the authors of all books in the store
//author $..author all authors
/store/* $.store.* all things in store, which are some books and a red bicycle.
/store//price $.store..price the price of everything in the store.
//book[3] $..book[2] the third book
//book[last()] $..book[(@.length-1)]
$..book[-1:]
the last book in order.
//book[position()<3] $..book[0,1]
$..book[:2]
the first two books
//book[isbn] $..book[?(@.isbn)] filter all books with isbn number
//book[price<10] $..book[?(@.price<10)] filter all books cheapier than 10
//* $..* all Elements in XML document. All members of JSON structure.

 

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>
			Insert title here
		</title>
	</head>
	<body>
		<script type="text/javascript" src="json.js"></script>
		<script type="text/javascript" src="jsonpath.js"></script>
		<script type="text/javascript">
			var json = {
				"MovieDatabase": {
					"movie": [{
						"name": "The Change-Up",
						"genre": "comedy",
						"director": "David Dobkin",
						"Facebook_like": 252
					},
					{
						"name": "Rise of the Planet of the Apes",
						"genre": "SciFi",
						"director": "Rupert Wyatt",
						"Facebook_like": 472
					},
					{
						"name": "30 Minutes or Less",
						"genre": "adventure",
						"director": "Ruben Fleischer",
						"Facebook_like": 114
					},
					{
						"name": "Final Destination 5",
						"genre": "Horror",
						"director": "Steven Quale",
						"Facebook_like": 241
					}]
				}
			}
		</script>
		
		<script type="text/javascript">
			var result = "";
			result = jsonPath(json, "$.MovieDatabase.movie[*].name").toJSONString();
			document.write(result);
			//output
			//["The Change-Up","Rise of the Planet of the Apes","30 Minutes or Less","Final Destination 5"] 
		</script>
	</body>

</html>

 

 

 

使用JSONP完成跨域请求

JSONP is used to request data from a server residing in a different domain. But why do we need a special technique to access data from a different domain? It's because of the Same Origin Policy.

Same Origin Policy 同源策略

In general, this policy states that, if protocol (like http), Port number (like 80) and host (like example.com) is different from where data is being requested, it should not be permitted.
But HTML <script> element is allowed to perform content retrieval from foreign origins.

 

JSONP is mostly used to get data using RESTFull APIs:

比如从 Flicker图片分享网站获取图片

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?

 

 

<!DOCTYPE html>
<html>
	<head>
		<style>
			img{ height: 100px; float: left; }
		</style>
		<script src="http://code.jquery.com/jquery-latest.js">
		</script>
		<title>
			An JSONP example from w3resource
		</title>
	</head>
	<body>
		<div id="images">
		</div>
		<script>
			$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
				tags: "dogs",
				tagmode: "any",
				format: "json"
			},
			function(data) {
				$.each(data.items,
				function(i, item) {
					$("<img/>").attr("src", item.media.m).appendTo("#images");
					if (i == 3) return false;
				});
			});
		</script>
	</body>

</html>
 
JSON
 

 

 

JSON的变体-MongoDB中存储数据所用的BSON

 

你可能感兴趣的:(json)