Ajude Jason a formatar seu JSON


11

Jason tem um grande JSON, mas é ilegível, então ele precisa fingir isso.

Especificação de formatação

O JSON tem 4 tipos diferentes:

  • Números; Somente0-9
  • Cordas; As "cordas com aspas duplas escaparam com\
  • Matrizes; Delimitado por [], com itens separados por ,, os itens podem ser qualquer um desses tipos
  • Objetos; Delimitado por {}, formato é key: valueonde chave é uma sequência e valor é um desses tipos

Espaçamento

  • As matrizes devem ter exatamente um espaço após as vírgulas entre os itens
  • Os objetos devem ter apenas um espaço entre a chave e o valor, após o :

Indentação

  • Cada nível de aninhamento é recuado 2 mais que o anterior
  • Cada par de chave / valor de objeto está sempre em sua própria linha. Os objetos são recuados
  • Uma matriz é recuada em várias linhas se contiver outra matriz ou objeto. Caso contrário, a matriz permanecerá em uma linha

Regras

  • Built-ins que trivializam essa tarefa não são permitidos.
  • Como sempre, brechas padrão não são permitidas

Exemplos

[1,2,3]
[1, 2, 3]
{"a":1,"b":4}
{
  "a": 1,
  "b": 4
}
"foo"
"foo"
56
56
{"a":[{"b":1,"c":"foo"},{"d":[2,3,4,1], "a":["abc","def",{"d":{"f":[3,4]}}]}]}
{
  "a": [
    {
      "b": 1,
      "c": "foo"
    },
    {
      "d": [2, 3, 4, 1],
      "a": [
        "abc",
        "def",
        {
          "d": {
            "f": [3, 4]
          }
        }
      ]
    }
  ]
}
[2,["foo123 ' bar \" baz\\", [1,2,3]]]
[
  2,
  [
    "foo123 ' bar \" baz\\",
    [1, 2, 3]
  ]
]
[1,2,3,"4[4,5]"]
[1, 2, 3, "4[4,5]"]
[1,2,3,{"b":["{\"c\":[2,5,6]}",4,5]}]
[
  1,
  2,
  3,
  {
    "b": ["{\"c\":[2,5,6]}", 4, 5]
  }
]

1
O JSON está analisando os buildins permitidos?
PurkkaKoodari #

Os objetos / matrizes podem estar vazios? Ainda podemos imprimir um espaço após vírgulas em matrizes se elas se dividirem em várias linhas?
Martin Ender

@ MartinBüttner não, e sim #
Downgoat

@ Pietu1998 hm, eu vou dizer não
Downgoat

Os idiomas do analisador de idiomas são permitidos?
Mama Fun Roll

Respostas:


1

JavaScript (ES6), 368 bytes

f=(s,r=[],i='',j=i+'  ',a=[])=>s<'['?([,,r[0]]=s.match(s<'0'?/("(?:\\.|[^"])*")(.*)/:/(\d+)(.*)/))[1]:s<'{'?(_=>{for(;s<']';s=r[0])a.push(f(s.slice(1),r,j));r[0]=s.slice(1)})()||/\n/.test(a)?`[
${j+a.join(`,
`+j)}
${i}]`:`[${a.join`, `}]`:(_=>{for(a=[];s<'}';s=r[0])a.push(f(s.slice(1),r,j)+': '+f(r[0].slice(1),r,j));r[0]=s.slice(1)})()||`{
${j+a.join(`,
`+j)}
${i}}`

Menos golfe:

function j(s, r=[], i='') { // default to no indentation
    if (s < '0') { // string
        let a = s.match(/("(?:\\.|[^"])*")(.*)/);
        r[0] = a[2]; // pass the part after the string back to the caller
        return a[1];
    } else if (s < '[') { // number
        let a = s.match(/(\d+)(.*)/);
        r[0] = a[2]; // pass the part after the string back to the caller
        return a[1];
    } else if (s < '{') { // array
        let a = [];
        while (s < ']') { // until we see the end of the array
            s = s.slice(1);
            a.push(j(s, r, i + '  ')); // recurse with increased indentation
            s = r[0]; // retrieve the rest of the string
        }
        r[0] = s.slice(1); // pass the part after the string back to the caller
        if (/\n/.test(a.join())) { // array contained object
            return '[\n  ' + i + a.join(',\n  ' + i) + '\n' + i + ']';
        } else {
            return '[' + a.join(', ') + ']';
        }
    } else { // object
        let a = [];
        while (s < '}') { // until we see the end of the object
            s = s.slice(1);
            let n = j(s, r, i + '  ');
            s = r[0].slice(1);
            let v = j(s, r, i + '  ');
            a.push(n + ': ' + v);
            s = r[0]; // retrieve the rest of the string
        }
        r[0] = s.slice(1); // pass the part after the string back to the caller
        return '{\n  ' + i + a.join(',\n  ' + i) + '\n' + i + '}';
    }
}
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.