Json - stringify以便数组在一行上

时间:2011-08-04 07:45:28

标签: json stringify

是否可以将JSON对象字符串化为这样,数组在一行中 - 不缩进

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

10 个答案:

答案 0 :(得分:10)

试试这个:

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);

答案 1 :(得分:3)

如果您要将短数组显示为单行,请考虑使用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}
  ]
}

答案 2 :(得分:1)

我采取的另一种方法: 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))

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

答案 3 :(得分:1)

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;
}

答案 4 :(得分: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"]
        },

答案 5 :(得分:0)

请注意,这使用lodash来检测数组和对象,这是另一种保留&#34; leaf&#34;的方法。对象紧凑在一行:

_.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"}
      ]
    }
  ]
}

答案 6 :(得分:0)

试试这个:

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, '"');

答案 7 :(得分:0)

这是一个对我有用的版本。我只需要单个项目或数字数组。但是下面的布尔值true会使所有数组变成一个内衬。

  

每个框架似乎都有自己的陷阱! :)

     

我真的很沮丧,直到我发现string.replace只在第一次出现时起作用。现在,我很高兴能找到解决方法!

某些其他解决方案似乎在节点上对我不起作用?但是,如果有一个更简单的解决方案可行,我会说吧!

const singleLineForNumericAndSingleItemArray = false;
let formatJsonVtStandard = function(key, value) {
    // Edit: Without checking if it is json, strings holding numbers turn to numbers.
    if (if (typeof(value) === 'string' && (value.startsWith("{") || value.startsWith("[")))) {
        try {
            value = JSON.parse(value);
        } catch (ex) {}
    }
    if (!Array.isArray(value)) {
        return value;
    }
    if (value.length === 0) {
        return value;
    }
    if (singleLineForNumericAndSingleItemArray) {
        // Only keep single items and integer arrays on one line
        if (value.length > 1 && value.some(function(v) { return !Number.isInteger(v); })) {
            return value;
        }
    }
    for (var index in value) {
        if (typeof(value[index]) === 'object') {
            return value; // Don't support arrays that contain objects (little too tricky of a shot)
        } else if (typeof(value[index]) === 'string') { // Keep the double quotes
            value[index] = '#¯\_(ツ)_/¯#"#¯\_(ツ)_/¯#' + value[index] + '#¯\_(ツ)_/¯#"#¯\_(ツ)_/¯#';
        }
    }
    return '#¯\_(ツ)_/¯#[#¯\_(ツ)_/¯#' + value.join('#¯\_(ツ)_/¯#,#¯\_(ツ)_/¯# ') + '#¯\_(ツ)_/¯#]#¯\_(ツ)_/¯#';
};

function prettyStringify(json, spacing) {
    const results = JSON.stringify(json, formatJsonVtStandard, 2);
    const results1 = results.split('\"#¯\_(ツ)_/¯#[#¯\_(ツ)_/¯#').join('[');   // string.replace is sidelined: does not replace all occurrences
    const results2 = results1.split('#¯\_(ツ)_/¯#]#¯\_(ツ)_/¯#\"').join(']');  // string.replace is sidelined: does not replace all occurrences
    const results3 = results2.split('#¯\_(ツ)_/¯#\\"#¯\_(ツ)_/¯#').join('\"'); // string.replace is sidelined: does not replace all occurrences
    const results4 = results3.split('#¯\_(ツ)_/¯#,#¯\_(ツ)_/¯#').join(',');    // string.replace is sidelined: does not replace all occurrences
    return results4;
}

答案 8 :(得分: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)
}));

答案 9 :(得分:-1)

一个旧问题的另一个现代答案:看看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许可开放的。