我正在尝试制作一个JSON来存储有关用户的信息。例如,最终它希望它看起来像:
{
"people": [
{
"name": "foo",
"company": "bar",
"email": "foo@bar.com"
},
{
"name": "bar",
"company": "foo",
"email": "bar@foo.com"
}
]
}
这将通过表单填充,因此我希望能够声明一个空的JSON并在人们提交表单时添加它。有没有办法用骨架(名称,公司,电子邮件)声明一个空的JSON?另外我如何添加另一个条目?是否有某种.append(“名称”:“酒吧”,“公司”:“foo”,“电子邮件”:“bar@foo.com”)?我想使用直接的javascript,但如果需要,使用jquery就可以了。
答案 0 :(得分:2)
使用Javascript,无需在JSON对象中预定义任何内容。
这是完全有效的代码:
var o = {}; // create a new object
o.name = "Bob";
console.log(o.name); // prints Bob
o.scores = new Array();
o.scores[o.scores.length] = 1;
o.scores[o.scores.length] = 2;
o.scores[o.scores.length] = 3;
console.log(o.scores); // prints [1, 2, 3]
o.info = {};
o.info.isSet = true;
console.log(o.info.isSet); // prints true
console.log(o.info.isNotSet); // prints undefined
因此,您可以从表单中动态构建所需的任何类型的JSON。
如果您想将JSON呈现为字符串,可以使用JSON.stringify(o)
,它将打印出来:
{"name":"Bob","scores":[1,2,3],"info":{"isSet":true}}
答案 1 :(得分:1)
使用Array.Push
var personInfo = {}; // Create the object and probably save it in
//localStorage or cookie etc or whatever pref you have,
//You can save it in `data` cache(of your HTML DOM element) too.
var peopleObj=[];
personInfo["people"] = peopleObj; //Save the array to the object onto the key/property "Person"
//Push the data as you need.
peopleObj.push({"name":"whatever",
"company":"foo",
"email":"bar@foo.com"
});
peopleObj.push({"name":"whatever2",
"company":"foo",
"email":"bar@foo.com"});
console.log(personInfo);
以下是您可能尝试实现的示例演示: - 使用localStorage存储骨架并在按钮单击时向其添加数据。
var personInfo = {
"people": []
};
window.localStorage.setItem('person',JSON.stringify(personInfo));
var i = 0;
$('input').click(function () {
var obj = JSON.parse(window.localStorage.getItem('person'));
obj["people"].push({
"name": "whatever" + i++,
"company": "foo",
"email": "bar@foo.com"
});
window.localStorage.setItem('person',JSON.stringify(obj));
console.log(obj);
});
答案 2 :(得分:1)
我建议创建一个功能来进行添加。它可以防止您在将人员添加到列表时复制所有添加代码。
// define your object somewhere
var someObject = {
"people": []
};
// define a function for adding to your main object
function addPerson(name, company, email) {
someObject.people.push({
"name": name,
"company": company,
"email": email
});
}
然后,当你想要添加另一个条目时,只需调用函数:
addPerson("Some Name", "A Company", "person@website.com");
对于类似这样的事情,我想说最好保持简单。
答案 3 :(得分:0)
我可能会这样做:
var Person = function (name, company, email)
{
this.name = name;
this.company = company;
this.email = email;
}
var People = function ()
{
this.people = [];
this.add = function (person)
{
this.people.push(person);
}
}
var people = new People();
people.add(new Person("john", "smith", "blah@blah.com"));
alert(JSON.stringify(people));