JS parsing JSON string as an object

Source: Internet
Author: User

The following sentence will directly parse the JSON string returned by the controller directly into a JSON object, without having to parse it two times.

$.ajax ({
Type: ' Post ',
dataType: ' JSON ',
Url:ctx + '/login/purchaselist?memberid= ' + MemberID,
Success:function (data) {
if (0 = = data.status) {
Alert (' No data! ‘);
} else {
var purchasearr = Data.jsonvalue;
for (var i = 0; i < purchasearr.length; i + +) {
alert (purchasearr[i].product_name);
}
}
}
});

@ResponseBody
@RequestMapping ("/purchaselist")
Public String purchaselist (Modelandview mav, long MemberID) {

String purchaseliststr = rdubbopropurchaseservice.findmemberpurchase (MemberID);
return purchaseliststr;
}

1) The first method

Data is a JSON string

var dataobj=eval ("(" +data+ ")");//Convert to JSON object

var jsonobj = eval (' (' + data + ') ');
var result = Jsonobj.result;
var MemberID = Jsonobj.memberid;

2) The second method

Parsing is done using a function object, the typical application of which is the success of the Ajax method in jquery and the parsing of the returned data.

var json= ' {' name ': ' CJ ', ' Age ': 18} ';

data = (New Function ("", "Return" +json)) ();

The data at this point is the one that will parse into a JSON object.

JS parsing JSON string as an object

Related Article

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.