Search code examples
javascriptjspjsp-tagshidden-field

Converting a map stored in hiddenput to JSON in JS


I am storing a Hashmap in JSP in a hiddeninput element

How can I parse it into a JSON object in my javascript??

When i print the hidden input variable value in my JS output is something like this:

{zipcode=560036, fmid=xyz, quantity=1}

Solution

  • It is better to pass a JSON string from server so you can easily parse. If you have a simple object structure like this (your example) you can try split it and take eack key/value pair. here is a example

    var mapAsStr = "{zipcode=560036, fmid=xyz, quantity=1}";
    var convertToObj = function(str) {
        var obj = {};
        str.replace(/\{|\}/g, '').split(',').forEach(function(pair) {
            var keyVal = pair.split("=");
            var key = keyVal[0].trim();
            var val = keyVal[1].trim();
            val = isNaN(val) ? val : parseFloat(val);
            obj[key] = val;
        });
        return obj;
    }
    console.log(convertToObj(mapAsStr));

    But note you can proceed with this only if you have a flat object structure with primitive values.