简体   繁体   中英

How to put an Array object into JSON?

I have written the following Javascript code. It's the best I could do to get my data formatted as valid JSON:

var roles = getSelectedRoles(); // returns an Array object

/* TODO: Find a better way to get the roles into my JSON data */
var rolesString = '["' + roles[0] + '"';
if (roles.length > 1)
    for (var i = 1; i < roles.length; i++)
        rolesString += ',"' + roles[i] + '"';
rolesString += ']';                        

var lid = $('#lid').val();

var json = '{ "id": "' + lid + '", "roles":' + rolesString + '}';

As you can see, I am building my JSON with string concatenation looping thru my Array object. This is so ugly and it seems like there ought to be a clean way of inserting my Array data into my JSON.

If its just inserting array object into another object then:

var selRoles = getSelectedRoles(); 
var lid = $('#lid').val();  
var json = {
 id:lid ,
 roles: selRoles
};

If you need the whole object to be represented as a String then you can use Douglas Crockford's JSON2.js to achieve the same.

Include the js file mentioned above in your page and then you use:

var jsonString = JSON.stringify(json) //json is from previous code.

Can you try:

<script type="text/javascript">
var jsonObj = {
    id: lid,//$('#lid').val()
    roles:roles // getSelectedRoles()
}
var jsonStr = json_encode(jsonObj);
</script>

You can find the function: json_encode at here

您可以使用角色数组的join函数:

var rolesString = '["' + roles.join('", "') + '"]';

当前的浏览器提供了JSON对象类型,可以使这种事情变得微不足道(JSON.stringify(obj))..例如,请参见此处

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM