The processing of JSON data in JS and the method of parsing JSON data detailed _javascript tips

Source: Internet
Author: User
Tags string format

JSON (JavaScript Object notation) is a lightweight data interchange format. It is based on a subset of ECMAScript. JSON uses a completely language-independent text format, but it also uses a family of C-language (c, C + +, C #, Java, JavaScript, Perl, Python, and so on). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parsing and generation (generally used to improve network transmission rate).

The rule of JSON is simple: an object is an unordered set of ' name/value pairs '. An object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each "name" is followed by a ":" (a colon), and the ' name/value ' pair is separated by a ', ' (comma). Specific details Reference http://www.json.org/json-zh.html

For a simple example:

JS Code

function Showjson () { 
var user = 
{ 
"username": "Andy", 
"age": " 
Info": {"tel": "123456", "" Cellphone ":" 98765 "}, 
" address ": 
[ 
{The city]:" Beijing "," postcode ":" 222333 "}, 
{" City ":" NewYork "," Postcode ":" 555666 "} 
] 
} 
alert (user.username); 
alert (user.age); 
alert (user.info.cellphone); 
alert (user.address[0].city); 
alert (User.address[0].postcode); 

This represents a user object that has attributes such as username, age, info, and address.

You can also use JSON to simply modify the data, and modify the example above

JS Code

function Showjson () { 
var user = 
{ 
"username": "Andy", 
"age": " 
Info": {"tel": "123456", "" Cellphone ":" 98765 "}, 
" address ": 
[ 
{The city]:" Beijing "," postcode ":" 222333 "}, 
{" City ":" NewYork "," Postcode ":" 555666 "} 
] 
} 
alert (user.username); 
alert (user.age); 
alert (user.info.cellphone); 
alert (user.address[0].city); 
alert (user.address[0].postcode); 
User.username = "Tom"; 
alert (user.username); 
}

JSON provides a json.js package that is introduced into the http://www.json.org/json.js and then can be converted to JSON data simply by using object.tojsonstring ().

JS Code

function Showcar () { 
var carr = new Car ("Dodge", "Coronet R/t", 1968, "Yellow"); 
Alert (carr.tojsonstring ()); 
} 
function car (make, model, year, color) { 
this.make = make; 
This.model = model; 
This.year = year; 
This.color = color; 
}

You can use Eval to convert JSON characters to object

JS Code

function Myeval () { 
var str = ' {' name ': ' Violet ', ' occupation ': ' character '} '; 
var obj = eval (' (' + str + ') '); 
Alert (obj.tojsonstring ()); 

or use the Parsejson () method

JS Code

function Myeval () { 
var str = ' {' name ': ' Violet ', ' occupation ': ' character '} '; 
var obj = Str.parsejson (); 
Alert (obj.tojsonstring ()); 
}

Below, use prototype to write a JSON Ajax example.

Write a servlet first (my name is Servlet.ajax.JSONTest1.java) and write a sentence.

Java code

Response.getwriter (). Print ("{\ name\": \ "violet\", \ "occupation\": \ "Character\"} ");

And then write an AJAX request in the page.

JS Code

function SendRequest () { 
var url = '/mywebapp/jsontest1 '; 
var mailajax = new ajax.request ( 
URL, 
{method 
: ' Get ', 
oncomplete:jsonresponse 
} 
); 
function Jsonresponse (originalrequest) { 
alert (originalrequest.responsetext); 
var myobj = OriginalRequest.responseText.parseJSON (); 
alert (myobj.name); 
}

Prototype-1.5.1.js provides a method of JSON, String.evaljson (), you can modify the above method without using Json.js

JS Code

function Jsonresponse (originalrequest) { 
alert (originalrequest.responsetext); 
var myobj = OriginalRequest.responseText.evalJSON (true); 
alert (myobj.name); 
}

JSON also provides a Java Jar Package Http://www.json.org/java/index.html API is also very simple, here's an example

Fill in the request parameters in JavaScript

JS Code

function SendRequest () { 
var carr = new Car ("Dodge", "Coronet R/t", 1968, "Yellow"); 
var pars = "car=" + carr.tojsonstring (); 

var url = "/mywebapp/jsontest1"; 
var mailajax = new ajax.request ( 
URL, 
{method 
: ' Get ', 
parameters:pars, 
oncomplete:jsonresponse 
} 
); 

Using the JSON request string can simply generate Jsonobject and parse, modifying the servlet Add JSON processing (to use Json.jar)

Java code

private void Doservice (HttpServletRequest request, httpservletresponse response) throws IOException { 
String s3 = Re Quest.getparameter ("Car"); 
try { 
Jsonobject jsonobj = new Jsonobject (S3); 
System.out.println (jsonobj.getstring ("model")); 
System.out.println (Jsonobj.getint ("Year")); 
} catch (Jsonexception e) { 
e.printstacktrace (); 
} 
Response.getwriter (). Print ("{\ name\": \ "violet\", \ "occupation\": \ "Character\"} "); 

You can also use Jsonobject to generate JSON strings and modify the servlet

Java code

private void Doservice (HttpServletRequest request, httpservletresponse response) throws IOException { 
String s3 = req Uest.getparameter ("Car"); 
try { 
Jsonobject jsonobj = new Jsonobject (S3); 
System.out.println (jsonobj.getstring ("model")); 
System.out.println (Jsonobj.getint ("Year")); 
} catch (Jsonexception e) { 
e.printstacktrace (); 
} 
Jsonobject Resultjson = new Jsonobject (); 
try { 
resultjson.append ("name", "Violet") 
. Append ("Occupation", "developer") 
. Append ("Age", new Integer); 
System.out.println (Resultjson.tostring ()); 
} catch (Jsonexception e) { 
e.printstacktrace (); 
} 
Response.getwriter (). Print (resultjson.tostring ()); 

JS Code

function Jsonresponse (originalrequest) { 
alert (originalrequest.responsetext); 
var myobj = OriginalRequest.responseText.evalJSON (true); 
alert (myobj.name); 
alert (myobj.age); 
}

Here is a key to introduce the JSON data processing in JS

1. JSON data structure (object and array)

JSON object: var obj = {"Name": "Xiao", "Age": 12};

JSON array: var objarray = [{' Name ': ' Xiao ', ' age ': 12},{' name ': ' Xiao ', ' Age ': 12}];

2, processing JSON data, dependent files are: jquery.js

3. Note: In the process of data transmission, JSON data is in the form of text, that is, string format;

JS language is the operation of JS objects;

So the conversion between JSON string and JS object is the key;

4. Data format

JSON string: var json_str = ' {' name ': ' Xiao ', ' Age ': 12} ';

Josn object: var obj = {"Name": "Xiao", "Age": 12};

JS object: Object {name: "Xiao", age:12}

5. Type conversion

JSON string-->js object, using the method:

Indicate:

Json_str and obj represent the data types in sub Heading 4 of this article;

obj = Json.parse (json_str);
obj = Jquery.parsejson (JSON_STR);

Note: Incoming malformed JSON string (for example: ' {name: ' Xiao ', age:12} ') throws an exception;

JSON string format, strict format: ' {' name ': ' Xiao ', ' Age ': 12} '

JS Object-->json String:

Json_str = JSON. Stringify (obj);

Note:

1, eval () is a JS native function, using the form: eval (' + ' {name: "Xiao", Age:12} ') '), is not safe, can not guarantee the conversion of the type to JS object;

2, the above 3 methods, have passed the Chrome browser test, the following is a screenshot of the test results;

JSON string-->js object;

JS Object-->json String:

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.