string to map object in javascript

孤人 提交于 2020-01-23 02:05:26

问题


var map = new Map();
map.set('key1','value1');
map.set('key2','value2');

console.log(map);
console.log(map.toString());
console.log(JSON.parse(map.toString()))
//Uncaught SyntaxError: Unexpected token o in JSON at position 1

Converted map object to string using toString() and now I am unable to convert to map object from string.


回答1:


To store a stringified result, better to use plain JSON object, however using Map you can create a array of entries and stringify that

var str = JSON.stringify(Array.from( map.entries()));

and then again you can parse the JSON string to array and construct a new Map

var map = new Map(JSON.parse(str))

var map1 = new Map();
map1.set('key1','value1');
map1.set('key2','value2');

var str = JSON.stringify(Array.from( map1.entries()));

//store the string somewhere or pass it to someone
//or however you want to carry it

//re construct the map again
var map2 = new Map(JSON.parse(str))

console.log('key1', map2.get('key1'));
console.log('key2', map2.get('key2'));

However, Array.from(map), or using will also return the same thing and can be used here, but someone cannot grantee what it's actually returns until execute it, on the other hand, getting an Iterator and then forming an array is more conventional and readable, however Array.from(map) might be a better solution. Also spread operator can be used over map [...map] or map.entries() [...map.entries()] to form the same array of entries.




回答2:


That's because the map.toString() prints [object Map] which is not parsable by JSON.parse

You should use JSON.stringify to achieve your objective

Corrected script

var map = new Map().set('key1','value1')
.set('key2','value2');

console.log(map);
//since the underlying type is array requires to be expanded [...map]
console.log(JSON.stringify([...map])); 

map2 = new Map(JSON.parse(JSON.stringify([...map])));

Remember: Maps are immutable objects, and the underlying type is an array, you have to reassign the map variable or chain the sets functions.

Full explanation can be found here: http://2ality.com/2015/08/es6-map-json.html




回答3:


var map = new Map();
map.set('key1','value1');
map.set('key2','value2');

console.log(map);
//Covert your map object into JSON object
var jsonObj=[];

map.forEach(function(val,key){
var tempObj={};
tempObj[key]=val;
jsonObj.push(tempObj)
})

console.log(JSON.stringify(jsonObj));
console.log(JSON.parse(JSON.stringify(jsonObj)))
//Uncaught SyntaxError: Unexpected token o in JSON at position 1


来源:https://stackoverflow.com/questions/45957670/string-to-map-object-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!