I searched JSON and HashMap, there are many questions about "how to convert json to hashmap". So, they are different, and how can i use hashmap in js?
-
JSON is a text based exchange format. If your question is related to JavaScript objects, please precisely state the problem you have.Denys Séguret– Denys Séguret2015-08-02 09:34:06 +00:00Commented Aug 2, 2015 at 9:34
-
thank you~! I think i got the answer. JSON is a text based object that different from HashMap.Albin Zeng– Albin Zeng2015-08-02 10:11:00 +00:00Commented Aug 2, 2015 at 10:11
2 Answers
Short answer would be “no”, because JSON is simply a interchange format written and parsable as a JavaScript object. If you want something like a hash map, you probably would just use an Object not-so-primitive, defining and deleting keys or values respectively:
var mapObj = {};
mapObj[key] = 'value';
delete mapObj[key];
There is also the Map object that might fit such an use, new in ES6:
var mapObj = new Map();
mapObj.set('key','value');
mapObj.get('key');
mapObj.delete('key');
You can serialize JavaScript objects by calling stringify on them and then parse them again:
var stringJSON = JSON.stringify(mapObj); // check your object structure for serializability!
var objsJSON = JSON.parse(stringJSON);
Serializing a Map is a bit different. If serialisable, you can do it anyway by using Array.from() and entries():
var strMap = JSON.stringify(Array.from(mapObj.entries()));
var mapObj = new Map(JSON.parse(strMap));
4 Comments
Map can not be stringified with JSON.stringify().Wikipedia article states clearly that JSON is just text:
[JSON] uses human-readable text to transmit data objects
JSON is stored inside strings in Javascript. Javascript objects are essentially hashmaps. You can use JSON.parse() to convert a JSON string to an object.