Create json/conversion string in JavaScript as JSON

Source: Internet
Author: User

Create a JSON object in JS:

1. Defining JSON objects directly

var employees ="firstName": "Bill", "LastName": "Gates""firstName": "George", "LastName": " Bush "firstName": "Thomas", "LastName": "Carter" }];
alert (employees[0].firstname); You can see the output as Bill

2. By stitching the string and then converting it to a JSON pair image.

Example 1:
1 varids=["1", "2", "3"];2  varnames=["One", "one", "three"];3 4  varJson= "[";5   for(vari=0;i<ids.length;i++){6json+={"id": ids[i], "name": Names[i]};7     if(i+1<ids.length) json+= ",";8      }9json+= "]";Ten      Onejson=Json.parse (JSON); AAlert (json[0]); -}

The above example 1 will be 11 Rows Json.parse (JSON); error. because Json.parse () This method can only convert a string to a JSON object. In the example above, JSON is not stitched as a string in line 6th, but in line 4th, JSON is a string concatenation. Part of this JSON variable is a string, part of an object, This is not a JSON string, so it resolves an error.

Json.parse () Usage:

var foo = ' [{' id ': ' 1 ', ' name ': ' "'"}] ';
var json2=json.parse (foo);
Alert (json2[0].id)

Foo is a string, so the conversion is correct.

Example 1 is changed to read as follows:

var ids=["1", "2", "3"var names=["One", "one", "three"var json= "["   for (var i=0;i<ids.length;i++) {    json+ = ' {"id": \ "' +ids[i]+ ' \", "name": \ "' + names[i]+ ' \ '} ';     if (i+1<ids.length) json+= ",";     } json+ = "]"; alert (JSON); JSON=json.parse (JSON); Alert (json[0].id);

Convert the JSON stitching in the loop body to a string, so it's OK.

Create json/conversion string in JavaScript as JSON

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.