The use of JSON in various languages

Source: Internet
Author: User
Tags scalar

1. JSON data format

JSON (JavaScript Object Notation)

Structurally, all the data can eventually be divided into three categories:
The first type is scalar (scalar), which is a separate string (string) or number (numbers), such as the single word "Beijing".
The second type is the sequence (sequence)/array (array)/list (list), called the JSON array, which is a number of related data that are tied together in a certain order, such as "Beijing, Tokyo".

The third type is mapping (map)/hash (hash)/dictionary (dictionary), called a JSON object, which is a name/value pair (name/value), called "Object" in json such as "Capital: Beijing".

This can be understood as follows:
1. The array is created with "[]" and the object is created with "{}";
2. Whether it is an array or an object, the elements are separated by ",";
3. Inside the object, the name and value of the (attribute) are separated by ":" and must be separated by ":", and the property name or value cannot exist separately;
4. Objects and arrays can be nested with each other

JSON is passed in the form of text, which is a string that can be understood as a string in which the content needs to be written in a particular format. In various programming languages, we are going to convert the JSON string into variables in various languages and manipulate it. Here's a brief introduction.

Use JSON2.1 PHP to construct JSON in 2.PHP (that is, convert PHP objects to JSON strings)

Example 1:createjson Object

$info Array (' number ' = ' 2 ', ' names ' = +array(' Everyday Updates ', ' Hot Pictures ', ' Latest technology ', ' information ', ' Product Pictures ', ' Brands '); $json = Json_encode ($info);

Results:

{"Number": "2", "Names": ["Everyday Updates", "Hot Pictures", "Latest Technology", "Information", "Product Pictures", " Brands "]}

Example 2:create JSON array

$array Array (0 = "Eric", 1 = +);   echo json_encode ($array);

The program will print out: ["Eric", 23]

Note: in PHP

1. Arrays, objects are created with an array, if there is only a value in the array, or the key in the array key-value pair is a number, it is transferred as an array in the JSON, if the key in the array key-value pair is a string, then it is transferred to the object in the JSON;
2. Whether it is an array or an object, the elements are separated by ",";
3. Inside the object, the name and value of the (attribute) are separated by "=";

2.2 PHP uses JSON (that is, to convert a JSON string into a PHP object)

Example 1:

$json = ' {' Foo-bar ': 12345} '; $obj = Json_decode ($json); Print $obj // 12345

Note: You can use Var_dump (Json_decode ($STR)) When you do not know the JSON format, to see what happens after the conversion

3. JS constructs the JSON string using JSON3.1 JS
//method I: Write a string that removes the quotation marksvarJsonobj = {Number:6, Names:[{name: "DAILY UPDATES"}, {name: "POPULAR PICTURES"}]};varJsontext =json.stringify (jsonobj);//Method II: Used in many cases of array elements, you can add array elements dynamically//get the request JSON data of the client    varTotalnumofpictures = 17; varNuminonepage = Req.body.number;//Number of pictures in one page    varStartIndex =Req.body.startIndex;//Create picture Array    varPictures = []; varPicture =NewObject (); Picture.name= "Vol.1"; Picture.url= "Http://t2.baidu.com/it/u=1790018557,3075089305&fm=21&gp=0.jpg"; Pictures.push (picture); //Create array dynamically Picture=NewObject (); Picture.name= "Vol.2"; Picture.url= "Http://t2.baidu.com/it/u=2602371353,2521141668&fm=21&gp=0.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.3"; Picture.url= "Http://t3.baidu.com/it/u=2280986867,1567705443&fm=21&gp=0.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.4"; Picture.url= "Http://t3.baidu.com/it/u=1821458190,3818067678&fm=21&gp=0.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.5"; Picture.url= "Http://t2.baidu.com/it/u=472744134,2285846599&fm=21&gp=0.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.6"; Picture.url= "Http://t2.baidu.com/it/u=3957952154,3084688128&fm=21&gp=0.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "VOL.7"; Picture.url= "Http://t1.baidu.com/it/u=2291760722,2270589689&fm=21&gp=0.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.8"; Picture.url= "Http://t3.baidu.com/it/u=2759709517,445035895&fm=21&gp=0.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.9"; Picture.url= "Http://t1.baidu.com/it/u=812989780,2797001786&fm=23&gp=0.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.10"; Picture.url= "Http://i3.hunantv.com/p1/20121127/1058553836.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "vol.11"; Picture.url= "Http://img.21cbh.com/uploadfile/2012/0824/20120824013832913.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "vol.12"; Picture.url= "Http://i3.cnfolimg.com/auto/3_906048.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "vol.13"; Picture.url= "Http://pic.yesky.com/imagelist/08/12/8093046_5924.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.14"; Picture.url= "Http://www.autotimes.com.cn/upload/admin/images/chezhan/beijing/2012/model/bsj-5.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.15"; Picture.url= "Http://i3.cqnews.net/news/attachement/jpg/site82/2011-04-29/5356167799388589428.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "Vol.16"; Picture.url= "Http://img.shendu.com/forum/201212/27/115921b05wp2ah1sg46bqa.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "vol.17"; Picture.url= "Http://www.atv.com.cn/bbs/data/attachment/forum/201105/28/160747a1ydwwcccwyhjuhj.jpg";    Pictures.push (picture); picture=NewObject (); Picture.name= "vol.18"; Picture.url= "Http://jpp2.imghb.com/pic/pic/12/37/21/1423016512372180_a602x602.jpg"; Pictures.push (picture); //Create JSON data    varJSON =NewObject (); Json.numofpages= 2; Json.number=Numinonepage; varPicturejson = [];  for(vari = StartIndex; i < Startindex+json.number; i++) {Picturejson.push (pictures[i]); } json.pictures=Picturejson; if(req.body.id==100) {res.send (json.stringify (JSON)); }
3.2 JSON string into JS object

JSON string:

  var str1 = ' {' name ': ' cxh ', ' sex ': ' Man '} ';

JS object:

var str2 = {"Name": "Cxh", "Sex": "Man"};

Convert from JSON string to JS object

(FA i) Varobj = Eval_r (' (' + str + ') ');

Explanation: Since JSON is started and ended in the way "{}", in JS, it is treated as a block of statements, so the purpose of the parentheses is to force the Eval function to force the expression in parentheses to be converted to an object when processing JavaScript code. Instead of being executed as a statement (statement).

(Law II) var obj = Str.parsejson ();

(Law III) varobj = Json.parse (str);

Then Str.name

4. Using Json4.1java in Javaconstructing a JSON string

Just write a string.

String requestcontent = "{" id ":" 1 "," sort ":" des "," Number ":" 9 "," StartIndex ":" 1 "}"; Try {           new  stringentity (requestcontent);           Entity.setcontentencoding ("UTF-8");           Entity.setcontenttype (//Set the request content type as JSON           catch  (unsupportedencodingexception E1) {           e1.printstacktrace ();} HttpResponse=httpclient.execute (HttpPost);
4.2 Convert JSON strings to Java objects (JSON object or Jsonarray)
// if it is {new  jsonobject (response); //  Jsonarray array = Obj.getjsonarray ("class");       // get jsonobject from Jsonarray Jsonobject obj = array.getjsonobject (0);

Determine if a key/value pair exists

if (Jobj.has ("Identity")) ...

The use of JSON in various languages

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.