如何在JS中以人类可读格式打印JSON字符串

问题描述 投票:0回答:4

我有一个Firebase实时数据库,该数据库读取传感器数据(每0.3秒更新一次)并将其显示在我的网页上。经过一些研究,我发现了“漂亮的印刷”。但是,这不是我追求的格式。现在,我的数据显示如下:{“ Moisture”:619}。我正在寻找的是:水分:619。从现在开始,每次更新数据库中的值时,此代码还将创建一个新的{“ Moisture”:619}。理想的情况是,如果更新了新值,则使其在潮湿后仅更改值,而不是再次显示整个内容。

我的代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/styles.css">

    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-storage.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-messaging.js"></script>

    <script>
      // Initialize Firebase
      var config = {
        apiKey: "xx",
    authDomain: "xx",
    databaseURL: "xx",
    projectId: "xx",
    storageBucket: "xx",
    messagingSenderId: "xx",
    appId: "xx"
      };
      firebase.initializeApp(config);
    </script>


  <script>

    var database = firebase.database();


    var ref = firebase.database().ref("plant-patrol/Moisture");
    ref.once("value")
    .then(function(snapshot) {
    var key = snapshot.key; // "plant-patrol"
    var childKey = snapshot.child().key; // "Moisture"
    });
  </script>

<script>
    var ref = firebase.database().ref();
ref.on("value", function(snapshot) {
   console.log(snapshot.val());
    var snapshotJSON = JSON.stringify(snapshot.val());
    var moisture = snapshotJSON;
    document.write(moisture);

}, function (error) {
   console.log("Error: " + error.code);
});
    </script>  

    <script src="/script.js" defer></script>
  </head>
</html>

希望有人可以帮助我,我已经在这个问题上苦苦挣扎了一段时间。

提前感谢!

javascript json firebase-realtime-database formatting pretty-print
4个回答
0
投票

您可以使用JSON.stringify并替换:

const json = {
  id: "1",
  employee_name: "Tiger Nixon",
  employee_salary: "320800",
  employee_age: "61",
  profile_image: ""
};
document.getElementById("app").innerHTML = JSON.stringify(json, (key, value) => (value || ''), 4).replace(/"([^"]+)":/g, '$1:');

const json = {
  id: "1",
  employee_name: "Tiger Nixon",
  employee_salary: "320800",
  employee_age: "61",
  profile_image: ""
};
document.getElementById("app").innerHTML = JSON.stringify(json, (key, value) => (value || ''), 4).replace(/"([^"]+)":/g, '$1:');
	<div id="app"></div>

0
投票

您可以使用pre标记显示格式化的json。

const json = {
  id: "1",
  employee_name: "Tiger Nixon",
  employee_salary: "320800",
  employee_age: "61",
  profile_image: ""
};
document.getElementById("app").innerHTML = JSON.stringify(json, (key, value) => (value || ''), 4).replace(/"([^"]+)":/g, '$1:');
	<div><pre id="app"></pre></div>

0
投票

您可以使用正则表达式删除[] {}“”个字符:

 snapshotJSON.replace(/[\[\]\{\}\"]+/g, '')

但是您已经具有普通值了>]

 snapshot.val()

所以为什么不使用它。

 JSON.stringify()

将javascript对象转换为JSON格式的字符串-通常用于机器对机器的通信。相反的是JSON.parse,可将文本转换为JavaScript对象。


0
投票

您可以使用漂亮的样式来样式化整个代码。

© www.soinside.com 2019 - 2024. All rights reserved.