如何在javascript / jquery中构建json字符串? [英] How can I build a json string in javascript/jquery?

查看:502
本文介绍了如何在javascript / jquery中构建json字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式构建一个json字符串。最终产品应该是这样的:

I would like to build a json string programmatically. The end product should be something like:

var myParamsJson = {first_name: "Bob", last_name: "Smith" };

但是我想一次做一个参数。如果它是一个数组,我会做类似的事情:

However I would like to do it one parameter at a time. If it were an array, I would just do something like:

var myParamsArray = [];
myParamsArray["first_name"] = "Bob";
myParamsArray["last_name"] = "Smith";

我甚至不介意构建该数组然后转换为json。有什么想法?

I wouldn't even mind building that array and then converting to json. Any ideas?

推荐答案

你可以用对象做类似的事情:

You could do a similar thing with objects:

var myObj = {};
myObj["first_name"] = "Bob";
myObj["last_name"] = "Smith";

然后你可以使用 JSON.stringify 将该对象转换为JSON字符串的方法。

and then you could use the JSON.stringify method to turn that object into a JSON string.

var json = JSON.stringify(myObj);
alert(json);

将显示:

{"first_name":"Bob","last_name":"Smith"}

这种方法本身内置于所有现代浏览器中(即使IE8远非现代浏览器,IE8也支持它)。如果你需要支持一些旧版浏览器,你可以包括 json2.js 脚本。

This method is natively built into all modern browsers (even IE8 supports it, even if IE8 is very far from being a modern browser). And if you need to support some legacy browsers you could include the json2.js script.

这篇关于如何在javascript / jquery中构建json字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆