0

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?

2
  • JSON is a text based exchange format. If your question is related to JavaScript objects, please precisely state the problem you have. Commented Aug 2, 2015 at 9:34
  • thank you~! I think i got the answer. JSON is a text based object that different from HashMap. Commented Aug 2, 2015 at 10:11

2 Answers 2

6

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));
Sign up to request clarification or add additional context in comments.

4 Comments

You should make clear that Map can not be stringified with JSON.stringify().
@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), a Map is not needed at all.
thank you ~. first question on stackoverflow, and truely got help.
@曾彬炜: You are welcome for the answer and at Stack Overflow. Make sure you always know how to ask and what to do if someone answers.
0

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.

1 Comment

thank you~! I will search answer in wikipedia before ask.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.