如何更改JSON中字段的顺序 [英] How to change the order of the fields in JSON
问题描述
场景:考虑我有一个JSON文档,如下所示:
Scenario: Consider I have a JSON documents as follows:
{
"name": "David",
"age" : 78,
"NoOfVisits" : 4
}
问题:我想更改文档中字段的顺序/顺序,例如我要age
,NoOfVisits
&然后最后是name
.
Issues: I wanted to change the sequence/order of the fields in the document, say I want age
, NoOfVisits
& then lastly name
.
到目前为止,我将值存储在临时变量中,删除了字段&重新创建相同的字段.由于重新分配不起作用:(
As of now I am storing the value in temporary variable, deleting the field & recreating the same field. Since the reassignment did not work :(
我是通过以下方式做到的:
I did it in following way:
temp = doc["age"];
delete doc['age'];
doc["age"] = temp;
temp = doc["NoOfVisits "];
delete doc['NoOfVisits '];
doc["NoOfVisits"] = temp;
temp = doc["name"];
delete doc['name'];
doc["name"] = temp;
这样我将获得所需的有序JSON文档.这个要求很特殊,但是我仍然想要一些有效的解决方案
So that I will get the desired ordered JSON document. This requirement is peculiar kind but still I want some efficient solution
问题:有人可以以有效的方式帮助您达成目标吗?
Question: Can someone help out with efficient way to achieve the same?
推荐答案
May be you could change this using JSON.stringify()
喜欢
var json = { "name": "David", "age" : 78, "NoOfVisits" : 4 };
console.log(json);
//outputs - Object {name: "David", age: 78, NoOfVisits: 4}
//change order to NoOfVisits,age,name
var k = JSON.parse(JSON.stringify( json, ["NoOfVisits","age","name"] , 4));
console.log(k);
//outputs - Object {NoOfVisits: 4, age: 78, name: "David"}
将所需的键顺序放入数组中并提供给函数.然后将结果解析回json. 这是一个样本小提琴.
put the key order you want in an array and supply to the function. then parse the result back to json. here is a sample fiddle.
这篇关于如何更改JSON中字段的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!