Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing elements of JSON object without knowing the key names

Here's my json:

{"d":{"key1":"value1",       "key2":"value2"}} 

Is there any way of accessing the keys and values (in javascript) in this array without knowing what the keys are?

The reason my json is structured like this is that the webmethod that I'm calling via jquery is returning a dictionary. If it's impossible to work with the above, what do I need to change about the way I'm returning the data?

Here's an outline of my webmethod:

<WebMethod()> _ Public Function Foo(ByVal Input As String) As Dictionary(Of String, String)     Dim Results As New Dictionary(Of String, String)      'code that does stuff      Results.Add(key,value)     Return Results End Function 
like image 978
Radu Avatar asked Feb 25 '11 05:02

Radu


People also ask

Can JSON have value without key?

Keys must be strings, and values must be a valid JSON data type: string.

How do I access elements in JSON?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

How do you check if a JSON object contains a key or not?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().

How can I get the key-value in a JSON object?

To get a JSON object's key and value in JavaScript, we can use the JSON. parse method to parse the JSON object string into a JavaScript object. Then we can get a property's value as we do with any other JavaScript object.


1 Answers

You can use the for..in construct to iterate through arbitrary properties of your object:

for (var key in obj.d) {     console.log("Key: " + key);     console.log("Value: " + obj.d[key]); } 
like image 92
Ates Goral Avatar answered Sep 27 '22 22:09

Ates Goral