使用 stringify 将 javascript 关联数组转换为 json 对象,反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7089118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a javascript associative array into json object using stringify and vice versa
提问by user882196
I have a javascript associative array like one below
我有一个像下面这样的 javascript 关联数组
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
I want to convert it using Stringify to json object. I want to know after conversion how the json object will look like.
我想使用 Stringify 将其转换为 json 对象。我想知道转换后 json 对象的样子。
Also when i have this object How I can convert it back to associative array again.
此外,当我拥有这个对象时,我如何再次将其转换回关联数组。
回答by Ray Toal
First of all, by making my_cars
an array and stringifying it, you don't get what you expect.
首先,通过创建my_cars
一个数组并将其字符串化,您不会得到您期望的结果。
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(JSON.stringify(my_cars));
This alerts []
.
这提醒[]
。
What you want is to start with {}
:
你想要的是开始{}
:
var my_cars= {};
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(JSON.stringify(my_cars));
This alerts
这提醒
{"cool":"Mustang","family":"Station Wagon","big":"SUV"}
To get your object back from the string, use JSON.parse()
.
要从字符串中取回您的对象,请使用JSON.parse()
.
var s = JSON.stringify(my_cars);
var c = JSON.parse(s);
alert(c.cool);
This alerts "Mustang".
这会提醒“野马”。
回答by user882196
No,But the user want to use array not json.
不,但用户想使用数组而不是 json。
Normal JavaScript arrays are designed to hold data with numeric indexes. You can stuff named keys on to them (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for. The JSON array data type cannot have named keys on an array.
普通 JavaScript 数组旨在保存带有数字索引的数据。您可以将命名的键添加到它们上(当您想要存储有关包含普通、有序、数字索引数据的数组的元数据时,这会很有用),但这不是它们的设计目的。JSON 数组数据类型不能在数组上具有命名键。
If you want named keys, use an Object, not an Array.
如果您想要命名键,请使用对象,而不是数组。
*来源
var test = []; // Object
test[0] = 'test'; //this will be stringified
Now if you want key value pair inside the array
现在,如果您想要数组中的键值对
test[1] = {}; // Array
test[1]['b']='item';
var json = JSON.stringify(test);
output
输出
"["test",{"b":"item"}]"
so you can use an index with array,so alternatively
所以你可以使用数组的索引,所以或者
var my_cars= [];
my_cars[0]={};
my_cars[0]["cool"]="Mustang";
my_cars[1]={};
my_cars[1]["family"]="Station Wagon";
my_cars[2]={};
my_cars[2]["big"]="SUV";
console.log(JSON.stringify(my_cars));
Output
输出
"[{"cool":"Mustang"},{"family":"Station Wagon"},{"big":"SUV"}]"
回答by jfriend00
Moving my comment into an answer so I can show you a code example.
将我的评论移到答案中,以便我可以向您展示代码示例。
These types of array are no-no's in javascript. You should ONLY use an object for non-numeric keys like this. Array indexes should be numbers. Javascript objects can use arbitrary values for keys (like in your example). Arrays happen to "appear" to work because Arrays themselves are objects, but you will not find normal Array methods will work on them. For example, look at this code example.
这些类型的数组在 javascript 中是禁忌。你应该只为这样的非数字键使用一个对象。数组索引应该是数字。Javascript 对象可以对键使用任意值(如您的示例中所示)。数组碰巧“似乎”起作用了,因为数组本身就是对象,但是您不会发现普通的数组方法可以对它们起作用。例如,看看这个代码示例。
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
alert(my_cars.length); // alerts 0
You have only added properties to the underlying object, not actually added elements to the Array. You should use an Object for this, not an Array. Javascript does not actually have an Associative Array. It has an Object who's properties can often be used like one would use an Associate Array in other languages. But, it's an Object, not an Array.
您只向底层对象添加了属性,实际上并未向数组添加元素。您应该为此使用对象,而不是数组。Javascript 实际上没有关联数组。它有一个对象,该对象的属性通常可以像使用其他语言中的关联数组一样使用。但是,它是一个对象,而不是一个数组。
回答by Marinos An
"JavaScript does not support arrays with named indexes"
The most close state to an associative array is an array with entries converted to properties (as in your case), so I provide a solution for this exact case.
与关联数组最接近的状态是条目转换为属性的数组(如您的情况),因此我为这种确切情况提供了解决方案。
The fun thing is that Chrome's console makes it feel like an associative array: ["cool":"Mustang", "family":"Station Wagon", "big":"SUV"]
(Check with F12
)
有趣的是,Chrome 的控制台让它感觉像是一个关联数组:(["cool":"Mustang", "family":"Station Wagon", "big":"SUV"]
检查F12
)
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";
let toAssociative=(keys, values)=>
values.reduce((acc, cv)=>{
acc[acc.shift()]=cv
return acc;
}, keys)
let fromAssociative = (assArr)=>({...assArr})
let serialized = JSON.stringify(fromAssociative(my_cars))
let o = JSON.parse(serialized)
let restored = toAssociative(Object.keys(o) , Object.values(o))
console.log("orig:",my_cars)
console.log("serialized:",serialized)
console.log("restored:",restored)
回答by TechMaze
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API. In the function you can now decide what to do with value of key is of a specific type.
如果由于某种原因您无法将数组转换为对象,例如您正在处理不想触及的大型框架或遗留代码,而您的工作只是添加需要 JSON API 使用的 som 功能,则应考虑使用 JSON .stringify(json,function(k,v){}) 版本的 API。在函数中,您现在可以决定如何处理特定类型的键值。