如何使用 JavaScript 將 JSON 字串轉換為 JSON 物件陣列?


JSON 用於在客戶端和伺服器之間交換資料。JSON 非常輕量級,易於人工閱讀,也易於機器解析和生成。很多時候我們獲取到的資料是以字串格式存在的,我們需要將這些資料轉換為陣列。在本文中,我們將討論使用 JavaScript 將 JSON 字串轉換為 JSON 物件陣列的多種方法。

  • 使用 JSON.parse( ) 方法

  • 使用 eval( ) 函式

方法 1:使用 JSON.parse( ) 方法

JSON.parse 方法用於將 JSON 字串轉換為 JSON 物件。這是一種非常快速且標準的處理 JSON 資料的方式。JSON.parse 以字串作為輸入,並根據輸入值的結構返回 JavaScript 值、物件、陣列、布林值、null 等。

示例

在這個示例中,我們有一個包含各種人員資料的 JSON 字串,我們將使用 JSON.parse 方法將其轉換為 JSON 物件。

<html>
<body>
   <h2>Convert JSON string to array of JSON objects using JSON.parse method</h2>
   <p>Click the following button to convert JSON string to an array of JSON objects</p><br>
   <button id="btn" onclick="convert( )" > Click Here </button> <br>
   <p id="result"> </p>
   <script>
      function convert(){
         
         // Initialize the dummy JSON String
         let jsonString = '[ { "name" : "Ram", "age" : 20, "car" : "ford" },{ "name": "Shyam", "age" : "21", "car" : "tata" }, { "name" : "Mohan", "age" : 22, "car" : "toyota" } ]'
         
         // Conver the JSON String to JSON object
         let jsonObject = JSON.parse(jsonString);
         
         // Get the paragraph element
         let p = document.getElementById("result")
         
         /// Print the Object
         p.innerText += JSON.stringify(jsonObject);
         
         // Print the Object on Console
         console.log(jsonObject)
      }
   </script>
</body>
</html>

方法 2:使用 eval( ) 函式

javascript 中的 eval( ) 函式是一個全域性函式,用於將字串評估為表示式。要使用 eval 函式將 JSON 字串轉換為 JSON 物件陣列,我們將 JSON 字串傳遞給它,該函式將返回 JSON 物件。

示例

在這個示例中,我們有一個包含各種人員資料的 JSON 字串,我們將使用 eval( ) 函式將其轉換為 JSON 物件。

<html>
<body>
   <h2>Convert JSON string to array of JSON objects using eval function</h2>
   <p>Click the following button to convert JSON string to an array of JSON objects</p><br>
   <button id="btn" onclick="convert( )" > Click Here </button> <br>
   <p id="result"></p>
   <script>
      function convert(){
         
         // Initialize the dummy JSON String
         let jsonString = '[ { "name" : "Ram", "age" : 20, "car" : "ford"},{ "name": "Shyam", "age" : "21", "car" : "tata" }, { "name" : "Mohan", "age" : 22, "car" : "toyota" } ]'
         
         // Conver the JSON String to JSON object
         let jsonObject = eval(jsonString);
         
         // Get the paragraph element
         let p = document.getElementById("result")
         
         /// Print the Object
         p.innerText += JSON.stringify(jsonObject);
         
         // Print the Object on Console
         console.log(jsonObject)
      }
   </script>
</body>
</html>

更新於: 2023年2月21日

10K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告