【发布时间】:2009-10-11 14:48:30
【问题描述】:
我有一个 JSON 文件 contact.txt,它已被解析为一个名为 JSONObj 的对象,其结构如下:
[
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
},
{
"firstName": "Mike",
"lastName": "Jackson",
"address": {
"streetAddress": "21 Barnes Street",
"city": "Abeokuta",
"state": "Ogun",
"postalCode": "10122"
},
"phoneNumbers": [
{ "type": "home", "number": "101 444-0123" },
{ "type": "fax", "number": "757 666-5678" }
]
}
]
我设想通过从表单中获取数据来编辑文件/对象,以便添加更多联系人。我该怎么做?
下面添加新联系人到JSONObj的数组的方法好像不行,有什么问题?:
var newContact = {
"firstName": "Jaseph",
"lastName": "Lamb",
"address": {
"streetAddress": "25 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "13021"
},
"phoneNumbers": [
{ "type": "home", "number": "312 545-1234" },
{ "type": "fax", "number": "626 554-4567" }
]
}
var z = contact.JSONObj.length;
contact.JSONObj.push(newContact);
【问题讨论】:
-
我根据您的回复更新了我的答案。
-
我更新了我原来的帖子,展示了我是如何尝试操纵 JSON 对象的。