如何使用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字符串转换为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字符串传递给eval函数,并且该函数返回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>