如何将JSON数组编码为JSON后如何编辑?
我想编辑以下JSON数组:
{"Status":"OK","Message":"API Call worked","Result":[{"interval":"2014-11-30",
"leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},
{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},
{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}]}
将其更改为此
{"Result":"OK","Records":[{"interval":"2014-11-30",
"leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},
{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},
{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}]}
如何在Javascript中编辑数组?
答案 0 :(得分:1)
如果真的希望用JavaScript执行此操作,您只需创建一个新的JavaScript对象(我在下面称之为newJSON
),并手动将其属性指定为属性您当前的JSON(我称之为oldJSON
):
var oldJSON = ...,
newJSON = {};
newJSON.Result = oldJSON.Status;
newJSON.Records = oldJSON.Result;
newJSON
现在是您想要的格式的JavaScript对象。如果我们就此致电JSON.stringify
,我们会看到结果。点击以下代码段中的运行代码段,以提醒您字符串化结果。
var oldJSON = {"Status":"OK","Message":"API Call worked","Result":[{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}]},
newJSON = {};
newJSON.Result = oldJSON.Status;
newJSON.Records = oldJSON.Result;
alert(JSON.stringify(newJSON));
答案 1 :(得分:0)
x['Records']=x.Result;
x['Result']=x.Status;
如果您不介意json中的一些额外键,那么您不需要删除它们,否则如果您想删除它们,请检查这些问题here。希望它有所帮助。
答案 2 :(得分:0)
也许您可以尝试修改和/或删除json密钥。
我会做这样的事情:
var json = '
{"Status":"OK",
"Message":"API Call worked",
"Result": [
{"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},
{"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},
{"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}]}
';
var obj = JSON.parse(json);
obj.Records = obj.Result;
delete obj.Result;
obj.Result = obj.Status;
delete obj.Status;
delete obj.Message;
json = JSON.stringify([obj]);
你会得到:
{"Records": [
{"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},
{"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},
{"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}
],
"Result":"OK"
}