特定的json字符串格式

时间:2017-07-28 17:59:02

标签: angularjs json

我有一个奇怪的要求,以非常精确的方式美化JSON结构。目前我正在使用angular.toJson(jsonObj,true)来自动美化它。

但是,我怎样才能进行自定义格式化。给出以下JSON:

  {"SomeArray": [
    {
      "Description": "Some sort of description",
      "a": 0,
      "b": "foo0",
      "c": "bar0"
    },
    {
      "a": 0,
      "b": "foo1",
      "c": "bar1",
      "d": "DoSomething1"
    },
    {
      "a": 0,
      "b": "foo2",
      "c": "bar2",
      "d": "DoSomething2"
    },
    {
      "Description": "Another description",
      "a": 0,
      "b": "foo3",
      "c": "bar3",
      "d": "DoSomething3"
    },
    {
      "a": 0,
      "b": "foo4",
      "c": "bar4",
      "d": "DoSomething4"
    }]}

如何将其格式化为完全如下所示?基本上我需要在它自己的单独行上保留“描述”键,而其他键位于它下面的一行上,同时保持大括号在同一行:

{"SomeArray": [
    { "Description": "Some sort of description",
      "a": 0, "b": "foo0", "c": "bar0" },
    { "a": 0, "b": "foo1", "c": "bar1", "d": "DoSomething1" },
    { "a": 0, "b": "foo2", "c": "bar2", "d": "DoSomething2" },
    { "Description": "Another description",
      "a": 0, "b": "foo3", "c": "bar3", "d": "DoSomething3" },
    { "a": 0, "b": "foo4", "c": "bar4", "d": "DoSomething4" }]}

1 个答案:

答案 0 :(得分:0)

想到我回过头来回答我是如何解决这个问题的。刚刚使用HandleBars.js。它是一个非常漂亮的模板引擎。我写了我希望json输出看起来的模板,然后只是传递了我想要格式化的对象。最终的结果就像我需要的那样格式化,只需很少的努力!

如果其他人因为某种原因正在努力格式化JSOn,我强烈建议您查看Handlebars。