1

I tried looking for a similar question, couldn't find anything detailed enough.

I have a an ajax call, which calls a php page and the response is:

echo json_encode($cUrl_c->temp_results);

Which outputs:

{"key":"value", "key2":"value"}

The output is being "parsed" using:

var json_response = JSON.parse(xmlhttp.responseText);

I was looking for a way to iterate through the response, and getting the key and value using javascript only.

  1. is the returned output considered valid json ?
  2. How do I loop through it (no jquery just javascript) ?

2 Answers 2

1

To iterate through the items of an object, you normally use a for..in loop, which let you access the keys (property names) as well as the property values:

for (var key in object) {
    var item = object[key];
}

And yes, {"key":"value", "key2":"value"} is valid JSON.

Sign up to request clarification or add additional context in comments.

Comments

0

To answer your first question, yes it is considered valid JSON once you parse it with JSON.parse(), as you have. To answer your second question, have a look at for...in from the MDN.

You could use the first example in the doc to find out how to get the keys and values.

Example 1

var o = {a:1, b:2, c:3};

function show_props(obj, objName) {
  var result = "";

  for (var prop in obj) {
    result += objName + "." + prop + " = " + obj[prop] + "\n";
  }

  return result;
}

alert(show_props(o, "o")); /* alerts: o.a = 1 o.b = 2 o.c = 3 */

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.