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 Aug 02 '15 at 09:34
-
thank you~! I think i got the answer. JSON is a text based object that different from HashMap. – Albin Zeng Aug 02 '15 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));

- 5,379
- 9
- 43
- 67
-
You should make clear that `Map` can not be stringified with `JSON.stringify()`. – Oliver Aug 02 '15 at 09:51
-
@Oskar: That is what I meant by “check for serializability”. The question is a bit broad, and if a simple `{}` suffices (which already is a [hash map](https://en.wikipedia.org/wiki/Hash_table)), a `Map` is not needed at all. – dakab Aug 02 '15 at 09:55
-
-
@曾彬炜: You are welcome for the answer and at Stack Overflow. Make sure you always know [how to ask](http://stackoverflow.com/help/how-to-ask) and what to [do if someone answers](http://stackoverflow.com/help/someone-answers). – dakab Aug 02 '15 at 10:17
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.