How to process an object literal?

眉间皱痕 提交于 2019-12-06 11:49:45

Does the following work:

o.results.result[0].title

to get the first result title? And to iterate over all results:

for (var i=0; i<o.results.result.length; i++) {
    var result = o.results.result[i];
    alert(result.title);
}

EDIT: Are you sure you copied it right? Here's what I get in Rhino:

js> o = {
  "query": {
  "count": "2",
  "created": "2009-07-25T08:17:54Z",
  "lang": "en-US",
  },
  "results": {
   "result": [
    {
     "abstract": "<b>Pizza</b> Hutr. Order Online for Delivery or Carry-out. Fast &amp; Easy.",
     "title": "<b>Pizza</b> Hut"
    },
    {
     "abstract": "Official site of Domino's <b>Pizza</b> delivery chain, which offers thin crust, deep dish, and hand tossed <b>pizzas</b> with a variety of side items and beverages. Site <b>...</b>",
     "title": "Domino's <b>Pizza</b>"
    }
   ]
  }
 }

js> o.results.result[0].title
<b>Pizza</b> Hut

I am not sure what the o parameter is in your callback function. I usually assign the XMLHttpRequest or ActiveXObject to a global var req.

Then use a callback:

 function json_callback() {
    if (req.readyState == 4) {
            if (req.status == 200) {
                    jsonObj = eval("(" + req.responseText + ")");
                    var out = document.getElementById('container');
                    out.innerHTML = jsonObj.query.count;
            }
       }
 }

It should be noted that you should only use eval() if you fully trust the server and the data the server is sending the client. There are JSON parsers available which are actually faster than eval() and also more secure as they limit it to only JSON whereas eval() can parse and execute all of JavaScript which could be a security risk. It is expected in the next version of ECMAScript that there will be a standard JSON parser built in.

The actual object has a slightly different structure than you wrote. results is actually an element of query. So try this:

o.query.results.result[0].title

As you can see from the JSON, the object has a property called "results" which contains a property called "result" which is an array of objects.

To display the first of that, you simply do as you already did with count, but just follow the structure to the title instead.

o.query.results.result[0].title

To loop over each result, you can simply loop over the result property like an array, for example like this:

var results = o.query.results.result;
for(var i = 0; i < results.length; i++) {

}

JSON is simply JavaScript code. Think of the JSON snippet as a JavaScript object declaration and you should have no problems understanding it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!