我试图用javascript编辑我的json文件。 我的json文件代码是
{
"contacts": {
"contact": {
"info": [
{
"id": "0",
"name": "name",
"number": "0",
"email": "email"
}
],
"messages": [
{
"message": [
{
"-from": "0",
"-to": "0",
"info": {
"id": "0",
"name": "name",
"number": "0",
"email": "email"
},
"text": [
{
"subText": {
"-italics": "false",
"-underline": "false"
}
}
],
"file": [
{
"-size": "0",
"-type": "image",
"fileInfo": {
"id": "0",
"name": "name",
"number": "0",
"email": "email"
}
}
]
}
]
}
]
}
}
}
我想设置contacts.contact.info.id的值,我想在contacts.contact.info中添加另一个数组。 PLZ帮我解释语法。 我在创建信息数组中创建新元素时遇到问题。 并告诉如何显示contacts.contact.info元素的值
答案 0 :(得分:2)
使用JavaScript,它非常简单:
var data = {};//your json string here
data.contacts.contact.info[0].id = 'New value here'; //id is in array
data.contacts.contact.info.push('Append this value to info');
//or
data.contacts.contact.info = 'Overwrite current info value';
//get string
console.log(JSON.stringify(data));
这就是全部。如果要手动更改数据:
{
"contacts": {
"contact": {
"info": [
{
"id": "0",//replace with, for example:
"name": "name",
"number": "0",
"email": "email"
},//add comma, and data below:
{
"id": "123",
"name": "foobar",
"number": "1"
},
"primitives go here, too"
],//end array
"messages": [...
这就是它的全部内容 按照您的要求保留漂亮的印刷:
var data = JSON.parse(yourString);
data.contacts.contact.info.push(
{"id": "7","name": "dg","number": "5454","email": "fsfsf"}
);
data.contacts.contact.info.push(
{"id": "8","name": "gjhhk","number": "64564","email": "fs54f"}
);
//get pretty string, using spaces for indentation:
console.log(JSON.stringify(data, null, ' '));
//same thing, but using tabs:
console.log(JSON.stringify(data, null, '\t'));
答案 1 :(得分:1)
你可以试试这个:
var json={contacts:{contact:{info:[{id:"0",name:"name",number:"0",email:"email"}],messages:[{message:[{"-from":"0","-to":"0",info:{id:"0",name:"name",number:"0",email:"email"},text:[{subText:{"-italics":"false","-underline":"false"}}],file:[{"-size":"0","-type":"image",fileInfo:{id:"0",name:"name",number:"0",email:"email"}}]}]}]}}};
console.log(json.contacts.contact.info[0]); //access first record
json.contacts.contact.info.push({id:"1",name:"name",number:"1",email:"abc@xyz.com"}); // add new info
console.log(json.contacts.contact.info);
答案 2 :(得分:0)
contacts.contact.info.id :
contacts.contact.info是一个数组..所以你必须按索引工作:
contacts.contact.info[0].id = newID;
添加到此数组:
contacts.contact.info.push(newArrayItem);
希望这能回答你的问题..