开发者

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

I'd like a JSON pretty printer that would recognize when an array or object fits on one line and just do that. Example:

{
  "fits": ["JSON", "pretty", "printer"],
  "longer": [
    "???????????????????????????????????????????????????",
    "???????????????????????????????????????????????????",
    "????????????????开发者_运维知识库???????????????????????????????????",
    "???????????????????????????????????????????????????",
    "???????????????????????????????????????????????????"
  ]
}

Is there a standalone library like this? If not, how would I go about writing one?

I'm most interested in a JavaScript implementation.


I don't know about any such concise JSON printer, but it shouldn't be hard to make your own if you want to:

  • You can use the for(property in object) to iterate over the properties of a given object.
    • Depending on use case, you might want to filter with hasOwnProperty.
  • You can determine if an reference points to an object, array, string or number with typeof
  • Have your pretty printer function receive the initial indentation offset and the object to be printed. This might be enough to decide if you should inline each property or not.
    • I'm not sure this "greedy" strategy is always "optimal" - perhaps it might be better to do something in multiple lines now to be able to inline later. I wouldn't worry with this at first though.


Since JSON is primarily a data transport format, I assume that you mean viewing raw JSON in the browser? If so, then there are a few options:

  • JSON Lint - Checks and reformats JSON
  • A pure JS version of the above
  • JSONView for Chrome
  • Safari JSON Formatter

You should be able to dig into the source of the last three if you require further customization. I'd start with iterating through the value.length property where value is/are the array element(s) to see if you can limit your output to a single line.


Use a replacer function to compare the total number of characters in each key/value pair to a fixed length. Here is a simple example:

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])
      }
    }
  }

Usage:

var json;

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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜