3431 Stimmen

JSON mit JavaScript hübsch ausdrucken

Wie kann ich JSON in einem leicht zu lesenden Format (für menschliche Leser) anzeigen? Ich bin in erster Linie für Einrückung und Leerraum, mit vielleicht sogar Farben / Schriftarten / etc.

26 Stimmen

Wenn Sie nur nach HTML ausgeben, können Sie es in eine <pre> Tag.

0 Stimmen

Alle Antworten funktionieren, aber Sie müssen Javascript verwenden :: var str = JSON.stringify(obj, null, 2); in html // <pre id="output_result_div"></pre >

0 Stimmen

Verwenden. Monaco-Editor um Ihr json anzuzeigen, ist im Jahr 2023 die bessere Wahl.

8voto

Das funktioniert gut:

console.table()

Lesen Sie hier mehr: https://developer.mozilla.org/pt-BR/docs/Web/API/Console/table

6voto

snovelli Punkte 5215

Konnte keine Lösung finden, die eine gute Syntaxhervorhebung für die Konsole bietet, daher hier meine 2p

Installieren & Hinzufügen der cli-highlight-Abhängigkeit

npm install cli-highlight --save

logjson global definieren

const highlight = require('cli-highlight').highlight
console.logjson = (obj) => console.log(
                               highlight( JSON.stringify(obj, null, 4), 
                                          { language: 'json', ignoreIllegals: true } ));

Verwenden Sie

console.logjson({foo: "bar", someArray: ["string1", "string2"]});

output

6voto

benshope Punkte 2866

Hier ist eine einfache JSON-Format / Farbe Komponente in React geschrieben:

const HighlightedJSON = ({ json }: Object) => {
  const highlightedJSON = jsonObj =>
    Object.keys(jsonObj).map(key => {
      const value = jsonObj[key];
      let valueType = typeof value;
      const isSimpleValue =
        ["string", "number", "boolean"].includes(valueType) || !value;
      if (isSimpleValue && valueType === "object") {
        valueType = "null";
      }
      return (
        <div key={key} className="line">
          <span className="key">{key}:</span>
          {isSimpleValue ? (
            <span className={valueType}>{`${value}`}</span>
          ) : (
            highlightedJSON(value)
          )}
        </div>
      );
    });
  return <div className="json">{highlightedJSON(json)}</div>;
};

Sehen Sie in diesem CodePen, wie es funktioniert: https://codepen.io/benshope/pen/BxVpjo

Ich hoffe, das hilft!

5voto

chim Punkte 7997

Wenn Sie nach einer netten Bibliothek suchen, um json auf einer Webseite zu verschönern...

Prism.js ist ziemlich gut.

http://prismjs.com/

Ich fand mit JSON.stringify(obj, undefined, 2), um die Einrückung zu erhalten, und dann mit Prism ein Thema hinzufügen war ein guter Ansatz.

Wenn Sie JSON über einen Ajax-Aufruf laden, können Sie eine der Utility-Methoden von Prism ausführen, um die Datei zu verschönern

Zum Beispiel:

Prism.highlightAll()

5voto

JohnPan Punkte 1070

Ich würde gerne meine jsonAnalyze Methode hier, wird eine hübscher Ausdruck der JSON-Struktur nur aber in einigen Fällen kann es nützlicher sein, als das gesamte JSON zu drucken.

Angenommen, Sie haben ein komplexes JSON wie dieses:

let theJson = {
'username': 'elen',
'email': 'elen@test.com',
'state': 'married',
'profiles': [
    {'name': 'elenLove', 'job': 'actor' },
    {'name': 'elenDoe', 'job': 'spy'}
],
'hobbies': ['run', 'movies'],
'status': {
    'home': { 
        'ownsHome': true,
        'addresses': [
            {'town': 'Mexico', 'address': '123 mexicoStr'},
            {'town': 'Atlanta', 'address': '4B atlanta 45-48'},
        ]
    },
    'car': {
        'ownsCar': true,
        'cars': [
            {'brand': 'Nissan', 'plate': 'TOKY-114', 'prevOwnersIDs': ['4532354531', '3454655344', '5566753422']},
            {'brand': 'Benz', 'plate': 'ELEN-1225', 'prevOwnersIDs': ['4531124531', '97864655344', '887666753422']}
        ]
    }
},
'active': true,
'employed': false,
};

Dann wird die Methode die Struktur wie folgt zurückgeben:

username
email
state
profiles[]
    profiles[].name
    profiles[].job
hobbies[]
status{}
    status{}.home{}
        status{}.home{}.ownsHome
        status{}.home{}.addresses[]
            status{}.home{}.addresses[].town
            status{}.home{}.addresses[].address
    status{}.car{}
        status{}.car{}.ownsCar
        status{}.car{}.cars[]
            status{}.car{}.cars[].brand
            status{}.car{}.cars[].plate
            status{}.car{}.cars[].prevOwnersIDs[]
active
employed

Dies ist also die jsonAnalyze() code :

function jsonAnalyze(obj) {
        let arr = [];
        analyzeJson(obj, null, arr);
        return logBeautifiedDotNotation(arr);

    function analyzeJson(obj, parentStr, outArr) {
        let opt;
        if (!outArr) {
            return "no output array given"
        }
        for (let prop in obj) {
            opt = parentStr ? parentStr + '.' + prop : prop;
            if (Array.isArray(obj[prop]) && obj[prop] !== null) {
                    let arr = obj[prop];
                if ((Array.isArray(arr[0]) || typeof arr[0] == "object") && arr[0] != null) {                        
                    outArr.push(opt + '[]');
                    analyzeJson(arr[0], opt + '[]', outArr);
                } else {
                    outArr.push(opt + '[]');
                }
            } else if (typeof obj[prop] == "object" && obj[prop] !== null) {
                    outArr.push(opt + '{}');
                    analyzeJson(obj[prop], opt + '{}', outArr);
            } else {
                if (obj.hasOwnProperty(prop) && typeof obj[prop] != 'function') {
                    outArr.push(opt);
                }
            }
        }
    }

    function logBeautifiedDotNotation(arr) {
        retStr = '';
        arr.map(function (item) {
            let dotsAmount = item.split(".").length - 1;
            let dotsString = Array(dotsAmount + 1).join('    ');
            retStr += dotsString + item + '\n';
            console.log(dotsString + item)
        });
        return retStr;
    }
}

jsonAnalyze(theJson);

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X