Are there any JSON printers that take extra care to be concise?

I would like a JSON-like printer to recognize when an array or object fits on one line, and just do it. Example:

{
  "fits": ["JSON", "pretty", "printer"],
  "longer": [
    "???????????????????????????????????????????????????",
    "???????????????????????????????????????????????????",
    "???????????????????????????????????????????????????",
    "???????????????????????????????????????????????????",
    "???????????????????????????????????????????????????"
  ]
}

Is there a separate library? If not, how would I start writing?

What interests me most is the JavaScript implementation.

+5
source share
3 answers

I don’t know about any such compressed JSON printer, but you can easily make your own if you want:

  • You can use for(property in object)to iterate over the properties of this object.
    • hasOwnProperty.
  • , , , typeof
  • . , , .
    • , "" "" - , - , . .
0

JSON - , , raw JSON ? , :

, . value.length, value / (-) , , .

0

replacer, / . :

function replacer(key, value)
  {
  var key_arr = [];
  var value_arr = [];
  var i = 0;
  for (_ in value)
    {
    key_arr.push(_);
    value_arr.push(value[_]);
    }
  for(;i < value_arr.length;i++)
    {
    if (key_arr[i].length + value_arr[i].length < 80)
      {
      console.log(key_arr[i] + ":" + "\t" + value_arr[i])
      }
    else
      {
      console.log(key_arr[i] + ":" + "\n" + value_arr[i])
      }
    }
  }

:

var json;

json = {"foo":"1","bar":"2"},      
JSON.stringify(json, replacer, 4);

json = {"foo":"12345678901234567890123456789012345678901234567890123456789012345678901234567890","bar":"2"};

JSON.stringify(json, replacer, 4);
0

All Articles