Sampo
Sampo

Reputation: 5048

How to generate minimum-size Javascript object?

How can I create a minimum-sized Javascript serialization of a Javascript object? Essentially a JSON.stringify with all unnecessary quotes removed. (Only basic JSON data types need to be supported, not Dates etc.)

For example, the JSON:

{
  "pi": 3.14,
  "e!": 4.26
}

would become:

{pi:3.14,"e!":4.26}

Edit: The result is not valid JSON, but is valid Javascript.

Upvotes: 2

Views: 565

Answers (1)

Taha Paksu
Taha Paksu

Reputation: 15616

Copied from https://stackoverflow.com/a/11233515/916000 and modified:

function stringify(obj_from_json) {
  if (typeof obj_from_json !== "object") {
    return JSON.stringify(obj_from_json);
  } else {
    if (Array.isArray(obj_from_json)) {
      // if the array contains an object
      var arr = [];
      for (var i = 0, len = obj_from_json.length; i < len; i++) {
        arr.push(stringify(obj_from_json[i]));
      }
      return "[" + arr.join(",") + "]";
    } else {
      var props = Object
        .keys(obj_from_json)
        .map(function(key) {
          return (new RegExp(/^[1-9a-zA-Z_$][a-zA-Z0-9_$.]*$/).test(key) ? key : "\"" + key + "\"") + ":" + stringify(obj_from_json[key]);
        }).join(",");
      return "{" + props + "}";
    }
  }
}


console.log(stringify({
  "pi": 3.14,
  "e!": 4.26
}));

console.log(stringify([{
  "adjacencies": [{
    "nodeTo": "graphnode2",
    "nodeFrom": "graphnode1",
    "data": {
      "$color": "#557EAA"
    }
  }],
  "data": {
    "$color": "#EBB056",
    "$type": "triangle",
    "$dim": 9
  },
  "id": "graphnode1",
  "name": "graphnode1"
}, {
  "adjacencies": [],
  "data": {
    "$color": "#EBB056",
    "$type": "triangle",
    "$dim": 9
  },
  "id": "graphnode2",
  "name": "graphnode2"
}]));

console.log(stringify({1: 2}));
console.log(stringify({"000": 42}));
console.log(stringify({1.26: 42}));

Edit: Added object array support. Edit: Fixed array conversion.

Upvotes: 1

Related Questions