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.
Antworten
Zu viele Anzeigen?Das funktioniert gut:
console.table()
Lesen Sie hier mehr: https://developer.mozilla.org/pt-BR/docs/Web/API/Console/table
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"]});
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!
Wenn Sie nach einer netten Bibliothek suchen, um json auf einer Webseite zu verschönern...
Prism.js ist ziemlich gut.
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()
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);
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.