如何使用 JavaScript 将 JSON 字符串转换为 JSON 对象数组?

JSON 用于从客户端到服务器交换数据。 JSON 非常轻量级,易于人类阅读,也易于机器解析和生成。很多时候我们获取字符串格式的数据,我们需要将该数据转换为数组。在本文中,我们将讨论使用 JavaScript 将 JSON 字符串转换为 JSON 对象数组的多种方法。
使用 JSON.parse( ) 方法
使用 eval( ) 函数
方法一:使用 JSON.parse( ) 方法
JSON.parse方法用于将JSON字符串转换为JSON对象。这是处理 JSON 数据的一种非常快速且标准的方法。 JSON.parse 将 String 作为输入,并根据输入值的结构返回 Javascript 值、对象、数组、布尔值、null 等。
示例
在此示例中,我们有一个包含各个人的数据的 JSON 字符串,我们将使用 JSON.parse 方法将该 JSON 字符串转换为 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 字符串转换为 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>
javascript