使用jquery解析JSON数据?

Pra*_*Raj 0 html jquery parsing json

我在解析从hello.json到当前html文件的json数据时遇到问题.

我如何从hello.json获得投资者,事件和价格的数据到三个单独的数组.

http://compliantbox.com/mobile/optionsedge/hi.html

请帮帮我!!!

这是我的HTML代码:

    <html>
    <head>
      <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
    </head>
    <body>
    <script>

    $.getJSON("http://compliantbox.com/mobile/optionsedge/hello.json?jsoncallback=?",
      {},
      function(data) { alert(data);  $.each(data.items, function(i,item){ alert(); });
      });
    </script>
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

这是我的json代码:

{ "data": 

{ 

"current_condition":[{

        "investors": [{"active"},{"agressive"},{"conservative"},{"day trader"},{"very active"}], 

        "events": [{"3 months"},{"weekly"},{"monthly"},{"leaps"},{"heaps"}], 

        "price": [{"4"},{"3"},{"9"},{"5"},{"2"}]

    } ] }}
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 6

更新3:我实际上只看了你的链接页面(总是将相关代码复制到问题本身),这是你的问题:

$.each(data.items, function(i,item){
  $("<html/>").attr("src", item.event);
  if ( i == 3 ) return true;
});
Run Code Online (Sandbox Code Playgroud)

data.items结果对象中没有反序列化您指向的(现在有效的)JSON.根本没有items.您的JSON描述了具有一个特性,一个对象data,这反过来有一个属性current_conditions,它与一个条目,与所述属性的对象的阵列investors,eventsprice.请参阅更新2中的代码,了解如何与其进行交互.

更新2:如果您更改JSON以使其有效,jQuery将起作用.我的意思是,每天都有成千上万的网站使用这个... 现场示例,您的数据被按下以使其有效.

更新:现在您已经发布了JSON,我们可以看到它无效.查看JSON站点和JSONlint工具.您的investors,, eventsprice数组都包含表单中的条目{"active"},这是一个无效的对象条目.


原答案:

如果您正在使用jQuery的ajax函数(或getJSON其他一个包装器),那么它应该在您看到它时进行解析.如果您必须自己解析JSON字符串,请使用parseJSON.细节:

ajax 和它的包装

扩展ajax事物:如果您正在返回一个字符串并期望一个对象(例如,解析JSON的结果),请确保服务器返回正确的内容类型("application/json").如果你无法控制的服务器,它的发回错误的内容类型,您可以通过给覆盖服务器ajax一个dataType选项.

如果它不起作用,您可能需要检查 - JSON真的是有效的JSON吗?因为那里有很多不完全JSON.例如,这是有效的JSON:

{
    "foo": 1,
    "bar": "x"
}
Run Code Online (Sandbox Code Playgroud)

不是:

{
    foo: 1,
    bar: 'x'
}
Run Code Online (Sandbox Code Playgroud)

严格的解析器可以拒绝后者,因为它是无效的(以几种不同的方式).

示例 - 正常,服务器配置正确的版本:

$.ajax({
   url: "yoururl",
   success: function(data) {
       // Here, `data` is already an object if the response was
       // JSON and the server gave the correct content-type
   }
});
Run Code Online (Sandbox Code Playgroud)

示例 - 强制数据类型:

$.ajax({
   url: "yoururl",
   dataType: "json",           // <== The new bit
   success: function(data) {
       // Here, `data` is already an object if the response was
       // parseable JSON
   }
});
Run Code Online (Sandbox Code Playgroud)

要么

$.getJSON("yoururl", function(data) {
   // Here, `data` is already an object if the response was
   // parseable JSON
});
Run Code Online (Sandbox Code Playgroud)

解析自己的字符串:

var str = '{"foo": 1, "bar": "x"}'; // A JSON string
var obj = jQuery.parseJSON(str);    // The resulting object
Run Code Online (Sandbox Code Playgroud)