如何使用 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>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP