JSON是一種取代XML的數據結構,和xml相比,它更小巧但描述能力卻不差,由于它的小巧所以網(wǎng)絡(luò )傳輸數據將減少更多流量從而加快速度, 那么,JSON到底是什么? About JSON and JSONP.
var str1 = '{ "name": "cxh", "sex": "man" }'; var data=eval("("+str1+")");//轉換為json對象//data =(new alert (data.name);//會(huì )顯示出cxh
不過(guò)eval解析json有安全隱患!
現在大多數瀏覽器(IE8及以上,Chrome和Firefox差不多全部)自帶原生JSON對象,提供JSON.parse()方法解析JSON,提供JSON.stringify()方法生成JSON,請使用這兩個(gè)方法!
如果擔心parse()對對象拋異常,可以加一個(gè)封裝函數:
JSON.pParse = function( tar ) { if( typeof( tar ) === 'string' ) { return JSON.parse( tar ); } else { return tar; } };
Thank you "My Local Buffoon" from oschina for the modification method.
為了方便地處理JSON數據,JSON提供了json.js包,下載地址: http://lib.sinaapp.com/js/json2/json2.js
In data transmission processes, JSON is transmitted as text, i.e., as a string. However, JS operates on JSON objects, so the conversion between JSON objects and strings is crucial. For instance:
JSON string:
var str1 = '{ "name": "cxh", "sex": "man" }';
JSON object:
var str2 = { "name": "cxh", "sex": "man" };
One: Convert a JSON string to a JSON object.
To use the above str1, it must be first converted into a JSON object.
var obj = eval('(' + str + ')');//由JSON字符串轉換為JSON對象
or else
var obj = str.parseJSON(); //由JSON字符串轉換為JSON對象
or else
var obj = JSON.parse(str); //由JSON字符串轉換為JSON對象
Then, it can be read like this:
Alert(obj.name); Alert(obj.sex);
Special attention: If obj is originally a JSON object, it remains a JSON object after being converted using the eval() function (even after multiple conversions), but it may raise syntax errors when processed with the parseJSON() function.
Two, use `toJSONString()` or `JSON.stringify()` globally to convert a JSON object to a JSON string.
For example:
var last=obj.toJSONString(); //將JSON對象轉化為JSON字符
or else
var last=JSON.stringify(obj); //將JSON對象轉化為JSON字符 alert(last);
Mindful:
Among the multiple principles listed above, the eval() function is native to JS, while the others come from the json.js package. The new JSON version has modified the API, integrating both JSON.stringify() and JSON.parse() into JavaScript's built-in objects. The former has become Object.toJSONString(), and the latter String.parseJSON(). If you're prompted that toJSONString() and parseJSON() are not found, it indicates that your json package version is too low.
Grammar:
jQuery.getJSON(url,data,success(data,status,xhr))
Parameters:
Parameter | Description |
---|---|
url | Must. Specify which URL to send the request to. |
data | Optional. Specifies the data sent along with the request to the server. |
success(data,status,xhr) |
可選。規定當請求成功時(shí)運行的函數。
額外的參數:
|
Use case:
$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });
這個(gè)需要json-lib.jar包支持 該jar下載地址: Click to download
//JSON對象 JSONObject的使用 String str1 = "{ 'name': 'cxh', 'sex': '1' }"; JSONObject obj = JSONObject.fromObject(str1); String name = obj.getString("name"); //直接返回字符串型 cxh Object nameo = obj.get("name"); //直接返回對象型的cxh int age = obj.getInt("sex"); //直接返回int型的sex //JSON數組對象 JSONArray的運用 String jsonArrStr = "[{ 'name': 'cxh', 'sex': '1','website':'http://www.bjljyy.com' },{ 'name': '三少', 'sex': '1','website':'http://www.ij2ee.com' }]"; JSONArray array = JSONArray.fromObject(jsonArrStr); int size = array.size(); //獲取JSON數組大小 JSONObject jo = array.getJSONObject(0);//取第一個(gè)JSON對象 for(int i=0;i<size;i++){ JSONObject jo1 = array.getJSONObject(i); System.out.println(jo1.getString("website")); //循環(huán)返回網(wǎng)址 } //序列化Bean對象為JSON對象 User user = new User(); user.setName("cxh"); user.setSex(1); user.setWebsite("http://www.bjljyy.com"); JSONObject jo2 = JSONObject.fromObject(user); System.out.println(jo2.toString()); //則會(huì )輸出 { 'name': 'cxh', 'sex': '1','website':'http://www.bjljyy.com' }
One, json_encode()
The function is mainly used to convert arrays and objects into JSON format. Let's look at an example of array conversion first:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr);
The result is:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Another example of object conversion:
$obj->body = 'another post'; $obj->id = 21; $obj->approved = true; $obj->favorite_count = 1; $obj->status = NULL; echo json_encode($obj);
The result is:
{ "body":"another post", "id":21, "approved":true, "favorite_count":1, "status":null }
Since JSON only accepts UTF-8 encoded characters, the parameters for json_encode() must be in UTF-8; otherwise, you'll get null or empty characters. Pay special attention to this when using GB2312 for Chinese or ISO-8859-1 for foreign characters.
2. Index and associative arrays
PHP supports two types of arrays: indexed arrays, which only store "values," and associative arrays, which store "name/value pairs." Since JavaScript does not support associative arrays, json_encode() converts indexed arrays into array format and associative arrays into object format. For instance, if there is an indexed array
$arr = Array('one', 'two', 'three'); echo json_encode($arr);
The result is:
["one","two","three"]
If it is changed to an associative array:
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three'); echo json_encode($arr);
The result then changed:
{"1":"one","2":"two","3":"three"}
注意,數據格式從"[]"(數組)變成了"{}"(對象)。
如果你需要將"索引數組"強制轉化成"對象",可以這樣寫(xiě):
json_encode( (object)$arr );
Or:
json_encode ( $arr, JSON_FORCE_OBJECT );
III. Class Conversion
Below is a PHP class:
class Foo { const ERROR_CODE = '404'; public $public_ex = 'this is public'; private $private_ex = 'this is private!'; protected $protected_ex = 'this should be protected'; public function getErrorCode() { return self::ERROR_CODE; } }
Now, perform a JSON conversion for an instance of this class:
$foo = new Foo; $foo_json = json_encode($foo); echo $foo_json;
Output result:
{"public_ex":"this is public"}
It can be seen that, except for public variables, everything else (constants, private variables, methods, etc.) is lost.
Four: json_decode()
The function is used to convert JSON text to the corresponding PHP data structure. Below is an example:
$json = '{"foo": 12345}'; $obj = json_decode($json); print $obj->{'foo'}; // 12345
By default, json_decode() always returns a PHP object instead of an array. For instance:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json));
The result is the generation of a PHP object:
object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }
If you want to force the generation of a PHP associative array, you need to add a parameter of "true" to json_decode().
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json,true));
Result in an associative array:
array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }
Five, common errors of json_decode()
$bad_json = "{ 'bar': 'baz' }"; $bad_json = '{ bar: "baz" }'; $bad_json = '{ "bar": "baz", }';
對這三個(gè)字符串執行json_decode()都將返回null,并且報錯。
第一個(gè)的錯誤是,json的分隔符(delimiter)只允許使用雙引號,不能使用單引號。第二個(gè)的錯誤是,json名值對的"名"(冒號左邊的部分),任何情況下都必須使用雙引號。第三個(gè)的錯誤是,最后一個(gè)值之后不能添加逗號(trailing comma)。
另外,json只能用來(lái)表示對象(object)和數組(array),如果對一個(gè)字符串或數值使用json_decode(),將會(huì )返回null。
var_dump(json_decode("Hello World")); //null
import json str1 = '{ "name": "cxh", "sex": "1" }' # 或者 # str1 = """{ "name": "cxh", "sex": "1" }""" # 或者 # str1 = "{ \"name\": \"cxh\", \"sex\": \"1\" }" obj = json.loads(str1) print(obj["name"]) print(obj["sex"]) # 由于出現中文,記得文件頭加入 # coding:utf8 json_arr_str = """[{ "name": "cxh", "sex": "1","website":"http://www.bjljyy.com" },{ "name": "我的", "sex": "1","website":"http://www.bjljyy.com" }]""" arr = json.loads(json_arr_str) for o in arr: print(o["name"]) print(o["sex"]) print(o["website"])
Thank you for the code provided by Zhang Donggui.
需要的dll:Newtonsoft.Json.dll, DLL official website download
//讀取簡(jiǎn)單的json string json="{\"username\":\"張三\"}"; string username = string.Empty; JObject jObj=JObject.Parse(json); //進(jìn)行格式化 username = jObj["username"].ToString(); Console.WriteLine(username); //讀取嵌套對象的json json = "{\"username\":\"張三\",data:{\"address\":\"福建廈門(mén)\"}}"; jObj = JObject.Parse(json); string address = string.Empty; address = jObj["data"]["address"].ToString(); Console.WriteLine(address); //讀取數組,操作方式與數組類(lèi)似 json = "{\"username\":\"張三\",data:[{\"address\":\"福建廈門(mén)\"},{\"address\":\"福建福州\"}]}"; jObj = JObject.Parse(json); address = string.Empty; address = jObj["data"][0]["address"].ToString()+","+ jObj["data"][1]["address"].ToString(); Console.WriteLine(address); Console.ReadLine();
Thank you for the code provided by Minghui Huang.
需要的dll:Newtonsoft.Json.dll, DLL official website download
//JSON字符串轉字典: NSString *str1 = @"{\"name\":\"cxh\",\"sex\":\"1\"}"; NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding]; NSError *error1; NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:&error1]; /* NSJSONReadingMutableContainers 創(chuàng )建結果為可變數組/字典 NSJSONReadingMutableLeaves 創(chuàng )建結果中字符串是可變字符串 NSJSONReadingAllowFragments 允許json最外層不是數組或字典 */ if (!error1) { NSLog(@"jsonDic is:%@",jsonDic); } else{ NSLog(@"error:%@",error1); } //字典轉JSON字符串 NSError *error2 = nil; NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:&error2]; if (!error2) { NSString *str2 = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding]; NSLog(@"json string is:%@",str2); } else{ NSLog(@"error:%@",error2); }
Please send any additional code and required libraries to my email at ij2ee@139.com. Those adopted can be accompanied by your website link.
You recently used: