What I want to do is read the JSON from a file and turn it into an array in Javascript.
My JSON looks like this
{
"3-2": "10",
"3-3": "20",
"3-4": "30",
"5-1": "4",
"5-3": "8"
}
I know I should include the code I'm working with, but I've tried so many different ways and I cannot get anything to even remotely work, so I'm just looking for a simple solution (I'm using jQuery).
I just want to fetch the content of my JSON file, turn it into an array, and then be able to run a for
loop to alert each item in the array.
CodePudding user response:
const json = '{"3-2":"10","3-3":"20","3-4":"30","5-1":"4","5-3":"8"}'
const obj = JSON.parse(json)
const arr = Object.entries(obj)
for (let i = 0; i < arr.length; i ) {
const [key, val] = arr[i]
console.log(`key: ${key}`)
console.log(`val: ${val}`)
}
CodePudding user response:
You can do it this way:
const yourJSON = {
"3-2": "10",
"3-3": "20",
"3-4": "30",
"5-1": "4",
"5-3": "8"
}
for (key in yourJSON)
console.log(key,":",yourJSON[key]) // here's your loop without converting into array