pretty-print JSON using JavaScript

后端 未结 24 1664
一向
一向 2020-11-21 06:45

How can I display JSON in an easy-to-read (for human readers) format? I\'m looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

24条回答
  •  清酒与你
    2020-11-21 07:00

    Here is a simple JSON format/color component written in React:

    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 (
            
    {key}: {isSimpleValue ? ( {`${value}`} ) : ( highlightedJSON(value) )}
    ); }); return
    {highlightedJSON(json)}
    ; };

    See it working in this CodePen: https://codepen.io/benshope/pen/BxVpjo

    Hope that helps!

提交回复
热议问题