[英]Convert data from JSON file to JavaScript Array?
我正在嘗試從看起來像這樣的 JSON 文件轉換數據:
[
{
"name": "Michael",
"age": "30",
"brithday": "11/10/1989",
}
]..... more data following
JavaScript 看起來像這樣:
var myArray = [
{'name':'Michael', 'age':'30', 'birthdate':'11/10/1989'},
{'name':'Mila', 'age':'32', 'birthdate':'10/1/1989'},
{'name':'Paul', 'age':'29', 'birthdate':'10/14/1990'},
{'name':'Dennis', 'age':'25', 'birthdate':'11/29/1993'},
{'name':'Tim', 'age':'27', 'birthdate':'3/12/1991'},
{'name':'Erik', 'age':'24', 'birthdate':'10/31/1995'},
]
你們對如何將 JSON 數據轉換為這種數組有任何想法嗎?
如果您已經將文件內容作為 JavaScript 字符串(我根據您的問題假設),您可以使用JSON.parse()
。 它將根據需要將 JSON 解析為 JavaScript 對象數組。
這是一個例子:
var text=`[ { "name": "Michael", "age": "30", "birthday": "11/10/1989" }, { "name": "Francine", "age": "38", "birthday": "03/12/1981" } ]`; var textAsArray = JSON.parse(text); console.log(textAsArray); // Will print the object array you asked for console.log(textAsArray[1].age); // Will print 38
console.log
語句只是為了向您展示它正在工作。
如果您需要將birthday
重命名為birthdate
,您可以這樣做:
textArray.forEach(element => {
element.birthdate = element.birthday;
delete element.birthday; // Just "cleaning up"
})
我遇到了你的問題,你在 javascript 中面臨的問題,以及它們的對象,在我看來,你有一些方法可以將數據從 JSON 文件轉換為數組,
方法 1-
First, you gonna do is to convert your JSON string to Javascript Array by using the JSON.parse()
Method and take all of the values of that object and push it using a for loop.
帶有代碼演示`
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 + "]"; }
`
方法二
這種方法也是相同的,但使用了不同的方法。 Convert the JSON string to the JavaScript object using eval()
method and then take out the values of the object and push them to the array using push()
method.
通過代碼演示。 ` 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 + "]"; }
`
使用這些方法,如果您在 HTML 中工作,它將解決您的問題......但是,
如果您正在使用框架,那么您將不得不在 node.js 中使用fs.readFile()
和其他文件系統算法。
在這里,您可以了解 - https://nodejs.dev/learn
這就是所有人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.