26

是否可以将 JSON 对象字符串化,使其看起来像这样,数组在一行中 - 不缩进

{
    "Repeat": {
        "Name": [["Top_level","All"],[[1,1]]],
        "Link": [["Top_level"],[[1,1]]]
    },
    "Delete": ["Confirm","Cancel"],
    "Move": ["Up","Down"],
    "Number": ["Ascending","Descending"]
}
4

9 回答 9

20

尝试这个:

var obj = {"Repeat": {"Name":[["Top_level","All"],[[1,1]]],"Link": [["Top_level"],[[1,1]]]},"Delete": ["Confirm","Cancel"],"Move": ["Up","Down"],"Number": ["Ascending","Descending"]};

JSON.stringify(obj,function(k,v){
   if(v instanceof Array)
      return JSON.stringify(v);
   return v;
},2);

结果:

"{
  "Repeat": {
    "Name": "[[\"Top_level\",\"All\"],[[1,1]]]",
    "Link": "[[\"Top_level\"],[[1,1]]]"
  },
  "Delete": "[\"Confirm\",\"Cancel\"]",
  "Move": "[\"Up\",\"Down\"]",
  "Number": "[\"Ascending\",\"Descending\"]"
}"
于 2013-08-26T20:48:20.570 回答
11

ericbowdenbigp得到答案,我生成了下面的函数,它允许我漂亮地打印 JSON,同时将数组保持在一行上,并将数组保持为数组形式,而不是将其转换为字符串。

function prettyPrintArray(json) {
  if (typeof json === 'string') {
    json = JSON.parse(json);
  }
  output = JSON.stringify(json, function(k,v) {
    if(v instanceof Array)
      return JSON.stringify(v);
    return v;
  }, 2).replace(/\\/g, '')
        .replace(/\"\[/g, '[')
        .replace(/\]\"/g,']')
        .replace(/\"\{/g, '{')
        .replace(/\}\"/g,'}');

  return output;
}
于 2019-02-28T17:44:15.190 回答
9

如果您打算将短数组显示为单行,请考虑使用json-stringify-pretty-compact。它产生如下结果:

{
  "bool": true,
  "short array": [1, 2, 3],
  "long array": [
    {"x": 1, "y": 2},
    {"x": 2, "y": 1},
    {"x": 1, "y": 1},
    {"x": 2, "y": 2}
  ]
}
于 2015-11-15T17:19:38.457 回答
6

我采取的另一种方法:

obj => JSON.stringify(obj, (k,v) => Array.isArray(v) ? JSON.stringify(v) : v, 2)
.replace(/"\[[^"\]]*]"/g, r => JSON.stringify(JSON.parse(r)).substr(1).slice(0,-1))

*数组不能包含字符串(注意正则表达式中不包含的“”),如果删除它,它将捕获键、值: "[": "[1,2,3,4]",

2020-03 更新 - 我制定了一个更稳定的解决方案

const obj = {
  "first_name": "John",
  "last_name": "Smith",
  "age": 21,
  "hobbies": [ "programming", "workout", null, undefined, 24, "\"has double quotes\"" ],
  "nested": {
    "arr": [ "one", "two", "three" ],
  },
  "nested_arr": [
    "first as string",
    {
      "latin": [ "alpha", "beta", "[gamma]" ]
    },
    null
  ]
};

const stringify = (obj, indent = 2) => 
  JSON.stringify(obj, (key, value) => {
    if (Array.isArray(value) && !value.some(x => x && typeof x === 'object')) {
      return `\uE000${JSON.stringify(value.map(v => typeof v === 'string' ? v.replace(/"/g, '\uE001') : v))}\uE000`;
    }
    return value;
  }, indent).replace(/"\uE000([^\uE000]+)\uE000"/g, match => match.substr(2, match.length - 4).replace(/\\"/g, '"').replace(/\uE001/g, '\\\"'));

console.log(stringify(obj));

于 2017-11-14T12:13:03.173 回答
3

尝试这个:

JSON.stringify(obj,function(k,v){
   if(v instanceof Array)
      return JSON.stringify(v);
   return v;
},4)
.replace(/"\[/g, '[')
.replace(/\]"/g, ']')
.replace(/\\"/g, '"')
.replace(/""/g, '"');
于 2017-09-14T11:00:04.040 回答
3

另一个老问题的现代答案:看看FracturedJson。该链接会将您带到 Web 版本,但它可以作为命令行应用程序以及 .NET 和 JS 库使用。

FracturedJson 将内联数组/对象,只要它们既不太长也不太复杂。它同样可以将数组拆分为多行,每行有多个项目。

这是一个使用默认设置的示例,但您可以将它们调整为最适合您的数据的任何设置。

{
    "SimpleItem": 77,
    "ComplexObject": {
        "Subthing1": {"X": 55, "Y": 19, "Z": -4},
        "Subthing2": { "Q": null, "W": [-2, -1, 0, 1] },
        "Distraction": [[], null, null]
    },
    "ShortArray": ["blue", "blue", "orange", "gray"],
    "LongArray": [
        2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 
        79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 
        163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 
        251, 257, 263, 269, 271, 277, 281, 283, 293
    ],
    "LongArray2": [
        [19, 2],
        [3, 8],
        [14, 0],
        [9, 9],
        [9, 9],
        [0, 3],
        [10, 1],
        [9, 1],
        [9, 2],
        [6, 13],
        [18, 5],
        [4, 11],
        [12, 2]
    ]
}

披露:我是 FracturedJson 的作者。它是在 MIT 许可下开源的。

于 2020-11-08T03:18:07.587 回答
1

请注意,这用于lodash检测数组和对象,这是另一种将“叶子”对象保持在一行上的方法:

_.jsonPretty = function(obj, indent) {
    if(!indent) indent = 2;

    return JSON.stringify(obj, function(k,v) {
        //Check if this is a leaf-object with no child Arrays or Objects:
        for(var p in v) {
            if(_.isArray(v[p]) || _.isObject(v[p])) {
                return v;
            }
        }

        return JSON.stringify(v);

        //Cleanup the escaped strings mess the above generated:
    }, indent).replace(/\\/g, '')
        .replace(/\"\[/g, '[')
        .replace(/\]\"/g,']')
        .replace(/\"\{/g, '{')
        .replace(/\}\"/g,'}');
};

就像这样使用它:

_.jsonPretty(yourObjectToStringify);

这是之前的一个例子......

{
  "type": "light-item",
  "name": "Waiting",
  "ringSeqLooping": true,
  "ringSeqHoldLast": false,
  "ringSteps": [
    {
      "type": "light-step",
      "time": 1,
      "audioClipName": "Off",
      "audioVolume": 1,
      "lights": [
        {
          "state": "FadeOn",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        }
      ]
    },
    {
      "type": "light-step",
      "time": "0.5",
      "audioClipName": "Off",
      "audioVolume": 1,
      "lights": [
        {
          "state": "FadeOff",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        }
      ]
    }
  ],
  "stripSeqLooping": true,
  "stripSeqHoldLast": false,
  "stripSteps": [
    {
      "type": "light-step",
      "time": "2",
      "audioClipName": "Off",
      "audioVolume": 1,
      "lights": [
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "FadeOn",
          "color": "#fff"
        },
        {
          "state": "FadeOn",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        }
      ]
    },
    {
      "type": "light-step",
      "time": "2",
      "audioClipName": "Off",
      "audioVolume": 1,
      "lights": [
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "FadeOff",
          "color": "#fff"
        },
        {
          "state": "FadeOff",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        },
        {
          "state": "Off",
          "color": "#fff"
        }
      ]
    }
  ]
}

...以及之后

{
  "type": "light-item",
  "name": "Waiting",
  "ringSeqLooping": "true",
  "ringSeqHoldLast": "false",
  "ringSteps": [
    {
      "type": "light-step",
      "time": "1",
      "audioClipName": "Off",
      "audioVolume": "1",
      "lights": [
        {"state":"FadeOn","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"}
      ]
    },
    {
      "type": "light-step",
      "time": "0.5",
      "audioClipName": "Off",
      "audioVolume": "1",
      "lights": [
        {"state":"FadeOff","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"}
      ]
    }
  ],
  "stripSeqLooping": "true",
  "stripSeqHoldLast": "false",
  "stripSteps": [
    {
      "type": "light-step",
      "time": "2",
      "audioClipName": "Off",
      "audioVolume": "1",
      "lights": [
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"FadeOn","color":"#fff"},
        {"state":"FadeOn","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"}
      ]
    },
    {
      "type": "light-step",
      "time": "2",
      "audioClipName": "Off",
      "audioVolume": "1",
      "lights": [
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"FadeOff","color":"#fff"},
        {"state":"FadeOff","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"},
        {"state":"Off","color":"#fff"}
      ]
    }
  ]
}
于 2017-02-22T01:23:09.953 回答
0

这是我制定的一个解决方案,它可以作为做类似事情的基础:

function labTab(ind){
    var tab,com,a;
    tab = "\t";
    com = [];
    for(a = 0; a < ind; a+=1){
        com.push(tab)
    }
    return com.join("");
}

function nsetEntry(tab,o,obj){
    return tab + '"'+ o + '":' + JSON.stringify(obj[o]);
}

function nsetObject(tab,o,obj,arr,ind){
    var start;
    start = tab + '"'+ o + '":{'; 
    return [start,nsetConstructor(obj[o],arr,ind)].join("\n") + "\n" + tab +"}"; 
}

function nsetConstructor(obj,arr,ind){
    var narr,tab,o,entry;
    narr = [];
    ind += 1;
    tab = labTab(ind);
    for(o in obj){
        if(obj[o].constructor === Object){
            entry = nsetObject(tab,o,obj,arr,ind);
            narr.push(entry); 
        }
        else{
            entry = nsetEntry(tab,o,obj);
            narr.push(entry);
        }
    }
    return narr.join(",\n");
}

function nsetLevels(obj,arr,ind){
    var o,start,tab;
    tab = labTab(ind);
    for(o in obj){
        if(obj[o].constructor === Object){
            entry = nsetObject(tab,o,obj,arr,ind);
            arr.push(entry); 
        }
        else{
            entry = nsetEntry(tab,o,obj);   
            arr.push(entry);
        }
    }
        return arr.join(",\n");
}

function nsetSave(){
    var json,o,ind,tab,obj,start,head,tail;
    json = [];
    for(o in nset){
        ind = 1;
        tab = labTab(ind);
        start = tab + '"'+ o + '":{';
        ind = 2;
        tab = labTab(ind);
        obj = nset[o];
        json.push([start,nsetLevels(obj,[],ind)].join("\n"))
    }
    head = "{\n";
    tail = "\n\t}\n}"
    FW.Write([head,json.join("\n\t},\n"),tail].join(""),"xset.json")
}

由于一些成员下降了五个级别,我无法弄清楚如何进行替换,所以我重新创建了整个事情。解决方案不是那么热,但我得到了我想要实现的目标 - 示例如下:

    "Key":{
        "Label":{
            "Change":["Input"],
            "Repeat":{
                "Name":[["Top_level","All"],[[1,1]]],
                "Link":[["Top_level"],[[1,1]]]
            },
            "Delete":["Confirm","Cancel"],
            "Move":["Up","Down"],
            "Number":["Ascending","Descending"]
        },
        "Class":{
            "Change":["Input"]
        },
于 2011-08-10T08:32:27.020 回答
0

我对我的应用程序的配置文件使用 JSON 格式。它们非常不同且足够大,因此需要不同的格式规则以使它们看起来更好和可读。不幸的是,提供的答案不够灵活,所以我制作了自己的实现,称为perfect-json来美化 JSON。

考虑到您想像这样格式化问题中的对象:

{
  "Repeat": {
    "Name": [
      ["Top_level", "All"],
      [[1, 1]]
    ],
    "Link": [
      ["Top_level"],
      [[1, 1]]
    ]
  },
  "Delete": ["Confirm", "Cancel"],
  "Move": ["Up", "Down"],
  "Number": [
    "Ascending",
    "Descending"
  ]
}

有了perfect-json它可以实现:

import perfectJson from 'perfect-json';

const obj = {
  Repeat: {
    Name: [['Top_level', 'All'], [[1, 1]]],
    Link: [['Top_level'], [[1, 1]]]
  },
  Delete: ['Confirm', 'Cancel'],
  Move: ['Up', 'Down'],
  Number: ['Ascending', 'Descending']
};

console.log(perfectJson(obj, {
  singleLine: ({ key, path, depth }) => {
    if (['Delete', 'Move'].includes(key)) {
      return true;
    }
    if (depth >= 3 && ['Name', 'Link'].includes(path[1])) {
      return true;
    }
    return false;
  }
}));

如问题中所述,将每个数组放在一行上也很容易:

console.log(perfectJson(obj, {
  indent: 4,
  singleLine: ({ value }) => Array.isArray(value)
}));
于 2021-07-27T13:37:07.280 回答