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

给定一个JSON字符串, 任务是将JSON字符串转换为JSON对象数组。此数组包含在JavaScript的帮助下从JSON字符串获得的JavaScript对象的值。有两种解决此问题的方法, 下面讨论:
方法1:首先使用将JSON字符串转换为JavaScript对象JSON.Parse()方法然后取出对象的值, 并使用将它们推入数组push()方法.
例子:

< !DOCTYPE HTML> < html > < head > < title > How to convert JSON string to array of JSON objects using JavaScript? < / title > < / head > < body style = "text-align:center; " > < h1 style = "color:green; " > lsbin < / h1 > < p id = "GFG_UP" > < / p > < button onclick = "myGFG()" > Click Here < / button > < p id = "GFG_DOWN" > < / p > < script > var up = document.getElementById("GFG_UP"); var JS_Obj = '{"prop_1":"val_1", "prop_2":"val_2", "prop_3" : "val_3"}'; up.innerHTML = "JSON string - '" + JS_Obj + "'"; var down = document.getElementById("GFG_DOWN"); function myGFG() { var obj = JSON.parse(JS_Obj); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = "Array of values - [" + res + "]"; } < / script > < / body > < / html >

【如何使用JavaScript将JSON字符串转换为JSON对象数组()】输出如下:
如何使用JavaScript将JSON字符串转换为JSON对象数组()

文章图片
方法二:此方法也相同, 但使用的方法不同。使用将JSON字符串转换为JavaScript对象eval()方法然后取出对象的值, 并使用将其推入数组push()方法.
例子:
< !DOCTYPE HTML> < html > < head > < title > How to convert JSON string to array of JSON objects using JavaScript? < / title > < / head > < body style = "text-align:center; " > < h1 style = "color:green; " > lsbin < / h1 > < p id = "GFG_UP" > < / p > < button onclick = "myGFG()" > Click Here < / button > < p id = "GFG_DOWN" > < / p > < script > var up = document.getElementById("GFG_UP"); var JS_Obj = '{"prop_1":"val_1", "prop_2":"val_2", "prop_3" : "val_3"}'; up.innerHTML = "JSON string - '" + JS_Obj + "'"; var down = document.getElementById("GFG_DOWN"); function myGFG() { var obj = eval('(' + JS_Obj + ')'); var res = []; for(var i in obj) res.push(obj[i]); down.innerHTML = "Array of values - [" + res + "]"; } < / script > < / body > < / html >

输出如下:
如何使用JavaScript将JSON字符串转换为JSON对象数组()

文章图片

    推荐阅读