Take an example.

JSON是一种取代XML的数据结构,和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度, 那么,JSON到底是什么? About JSON and JSONP.

JavaScript JSON methods

var str1 = '{ "name": "cxh", "sex": "man" }';
var data=eval("("+str1+")");//转换为json对象//data =(new
alert (data.name);//会显示出cxh

不过eval解析json有安全隐患!
现在大多数浏览器(IE8及以上,Chrome和Firefox差不多全部)自带原生JSON对象,提供JSON.parse()方法解析JSON,提供JSON.stringify()方法生成JSON,请使用这两个方法!
如果担心parse()对对象抛异常,可以加一个封装函数:

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.js methods for operating JSON

为了方便地处理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.

Get JSON method using jQuery

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) 可选。规定当请求成功时运行的函数。
额外的参数:
  • Response - Contains result data from the request
  • quo statu inclusum petitionis requisitum?
  • xhr - contains XMLHttpRequest object

Use case:

$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });

Java JSON Methods

这个需要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.bejson.com' },{ 'name': '三少', 'sex': '1','website':'http://www.ij2ee.com' }]";
JSONArray array = JSONArray.fromObject(jsonArrStr);
int size = array.size(); //获取JSON数组大小
JSONObject jo = array.getJSONObject(0);//取第一个JSON对象
for(int i=0;i<size;i++){
    JSONObject jo1 = array.getJSONObject(i);
    System.out.println(jo1.getString("website")); //循环返回网址
}

//序列化Bean对象为JSON对象
User user = new User();
user.setName("cxh");
user.setSex(1);
user.setWebsite("http://www.bejson.com");
JSONObject jo2 =  JSONObject.fromObject(user);
System.out.println(jo2.toString()); //则会输出 { 'name': 'cxh', 'sex': '1','website':'http://www.bejson.com' }

PHP handle JSON methods

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

注意,数据格式从"[]"(数组)变成了"{}"(对象)。
如果你需要将"索引数组"强制转化成"对象",可以这样写:

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", }';

对这三个字符串执行json_decode()都将返回null,并且报错。
第一个的错误是,json的分隔符(delimiter)只允许使用双引号,不能使用单引号。第二个的错误是,json名值对的"名"(冒号左边的部分),任何情况下都必须使用双引号。第三个的错误是,最后一个值之后不能添加逗号(trailing comma)。
另外,json只能用来表示对象(object)和数组(array),如果对一个字符串或数值使用json_decode(),将会返回null。

var_dump(json_decode("Hello World")); //null

Python operates on JSON methods.

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.bejson.com" },{ "name": "我的", "sex": "1","website":"http://www.bejson.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.

C# methods for operating JSON

需要的dll:Newtonsoft.Json.dll, DLL official website download

//读取简单的json
string json="{\"username\":\"张三\"}";
string username = string.Empty;
JObject jObj=JObject.Parse(json); //进行格式化
username = jObj["username"].ToString();
Console.WriteLine(username);


//读取嵌套对象的json
json = "{\"username\":\"张三\",data:{\"address\":\"福建厦门\"}}";
jObj = JObject.Parse(json);
string address = string.Empty;
address = jObj["data"]["address"].ToString();
Console.WriteLine(address);

//读取数组,操作方式与数组类似
json = "{\"username\":\"张三\",data:[{\"address\":\"福建厦门\"},{\"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.

Objective-C JSON Methods

需要的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 创建结果为可变数组/字典
 NSJSONReadingMutableLeaves 创建结果中字符串是可变字符串
 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);
}

Others

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:

收藏: favorite Menu QQ