Parse Soy

Parse a string with pseudo-JSON-data that lacks quotes around string values (as created by Soy templates) so that it can be properly parsed into JavaScript data

by Patrick Hund

HTML

<div id="sio-condition" data-soy-conditions="[{param: usage, value: NEW, label: Neu, count: 3, checked: false}, {param: usage, value: USED, label: Gebraucht, count: 1, checked: false}]"></div>

JavaScript

var rex1 = /[a-z0-9][^,\]}:]*/gi,
    rex2 = /^(true|false|[.0-9]+)$/,
    conditionsStr = $("#sio-condition").data("soy-conditions"),
    conditions;

conditionsStr = conditionsStr.replace(rex1, function (value) {
    if (value.match(rex2) === null) {
        return "\"" + value + "\"";
    }
    return value;
});

console.log(conditionsStr);

conditions = JSON.parse(conditionsStr);

console.log(conditions);