Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
How to use variables in JavaScript dot syntax? (with JSON)?
Right say I have a json file:
json = {"object1" : [{"item1": "value1", "item2": "value1"}, {"item1": "value1", "item2": "value1"}],
"object2" : [{"item1": "value1", "item2": "value1"}, {"item1": "value1", "item2": "value1"}],
"object3" : [{"item1": "value1", "item2": "value1"}, {"item1": "value1", "item2": "value1"}]
}
The values are irrelevant, and an array:
arr = Array("object1", "object2", "object3")
How would I use the values in the array to select the corrosponding value in the JSON?
I tried json.arr[0].item1(etc...) as that'd be the only way I can think of doing it but it didn't work.
The object names are put into an array via a for loop on the json file.
I found a work around which involves jQuery $.each() loops.
Neither of the given answers worked :(
2 Answers
- 1 decade agoFavorite Answer
You will first need to evaluate the arr[index] before this can be referenced via dot notation.
I believe this will work
var workingArray = json.eval(arr[0])[1].item1 (looking for array index 1 of array index 0 variable)
but you may need to first evaluate arr[index] using the eval function and set this as a variable then evaluate the JSON object variable you are looking for
- DarnentalLv 41 decade ago
You're using the wrong syntax to access the JSON objects. The JSON object contains members, not an array. Rewrite the JSON so that the start and end brackets are square brackets instead.
json = ["object1" : [{"item1": "value1", "item2": "value1"}, {"item1": "value1", "item2": "value1"}],
"object2" : [{"item1": "value1", "item2": "value1"}, {"item1": "value1", "item2": "value1"}],
"object3" : [{"item1": "value1", "item2": "value1"}, {"item1": "value1", "item2": "value1"}]
]
Now you can use - json[0].item1...