Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create json string from js Map and String

My REST controller expects request input of the following format, which it successfully converts to a Java object containing a Map and a String as parameters:

{ 
"myMap" : { 
    "key1": "value1", 
    "key2": "value2", 
    "key3": "value3"},
"myString": "string value"
}

I am getting my data from an html form like so:

var myMap = new Map();
var String = document.getElementById('String').value;
for (var i = 0 ; i<anArray.length ; i++){
    var input = document.getElementsByClassName('input_' + (i+1));
    for (var j = 0 ; j<3 ; j++){
        if (input[j].checked){
            myMap.set(input[j].name, input[j].id);
        }
    }
}

Basically, this code boils down to:

var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");

This results in a map containing {key1 => value1, key2 => value2, etc} and a String. I have been trying to turn this into a json string like so, but it doesn't seem to work:

var myJson = {};
myJson.myMap = myMap;
myJson.myString = myString;
var json = JSON.stringify(myJson);

However, I am ending up with the following string: `{"myMap":{},"String":"myString"}' . So I probably have to do something different to stringify a map, but nothing I try is working.

Can anyone help me out?

like image 690
I.Brok Avatar asked Jun 24 '17 19:06

I.Brok


People also ask

How do I create a JSON string?

var obj = new Object(); obj.name = "Raj"; obj. age = 32; obj. married = false; var jsonString= JSON. stringify(obj);

Can we convert map to JSON?

We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple.

What is toJSON () in JSON?

The toJSON() method returns a date object as a string, formatted as a JSON date. JSON dates have the same format as the ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ.


2 Answers

Using ES6 syntax, and especially if you have nested maps (otherwise Idan Dagan's answer is simpler), you can use the JSON.stringify()'s second argument, the reducer, as follows:

JSON.stringify(myMap, (key, value) => (value instanceof Map ? [...value] : value));

like image 153
Thaelvyn Avatar answered Sep 20 '22 13:09

Thaelvyn


This hack will do the job (but it's a global override and must be used carefully):

  Map.prototype.toString = function() {

    let result = {};

    this.forEach((key, value) => { result[key] = value;});

    return JSON.stringify(result);
  };
like image 36
Agustí Sánchez Avatar answered Sep 23 '22 13:09

Agustí Sánchez