【问题标题】:How to beautify parsed JSON in ReactJS? [duplicate]如何在 ReactJS 中美化解析的 JSON? [复制]
【发布时间】:2021-10-08 10:31:42
【问题描述】:

我正在尝试创建一个接受自定义 .xml 文件并使用 xml2json-ltx 库将其中的内容解析为 JSON 对象的 XML 到 JSON 转换器应用程序。我已经完成了解析/转换部分,但结果 JSON 有点难看。

我只想美化解析后的 JSON 并在生成的 JSON 对象中添加适当的缩进。我怎样才能?请用一个例子评论/回答:)

LtxParser.jsx

import React, { useState, useEffect } from "react";
import parser from "xml2json-ltx";
const Ltx = () => {
  const [fileState, setFileData] = useState();
  const [jsonData, setJsonData] = useState();

  useEffect(() => {
    if (!!fileState) {
      const resultObj = parser.toJson(fileState, {
        object: true,
      });
      setJsonData(resultObj);
    }
  }, [fileState]);
  const onFileDrop = (e) => {
    e.preventDefault();
    const fileData = e.target.files[0];
    const reader = new FileReader();
    reader.onload = function (evt) {
      setFileData(evt.target.result);
    };
    reader.readAsText(fileData);
  };

  return (
    <div>
      Ltx
      <input type="file" onChange={onFileDrop} />
      {jsonData && JSON.stringify(jsonData, undefined, 4)}
    </div>
  );
};

export default Ltx;

示例.xml

<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
</book>
</catalog>

【问题讨论】:

标签: json reactjs


【解决方案1】:

如评论和其他 SO 答案中所述,您可以使用 pre-tag 并在 pre-tag 内显示字符串化的 JSON 对象来显示换行符、缩进等,就像在解析的数据中一样。

例如:

<div>
      Ltx
      <input type="file" onChange={onFileDrop} />
      <pre>
        {jsonData && JSON.stringify(jsonData, undefined, 4)}
      </pre>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多