【问题标题】:JSON parsing with Javascript and jQuery [closed]使用 Javascript 和 jQuery 解析 JSON [关闭]
【发布时间】:2013-05-03 07:01:53
【问题描述】:
bfunc({   
"query": {   
  "count": 1,   
  "created": "2013-05-03T06:20:01Z",   
  "lang": "en-US",   
  "diagnostics": {   
  "publiclyCallable": "true",   
  "cache": {    
    "execution-start-time": "32",   
    "execution-stop-time": "32",   
    "execution-time": "0",   
    "method": "GET",   
    "type": "MEMCACHED",   
    "content": "http://www.vtualerts.com/robots.txt"   
   });

这是我需要使用 javascript 和 jQuery 解析的 JSON 数据。我试着这样做......

<div id="placeholder"></div>    
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>   
<script>   
$.getJSON('myjson.json', function(data) {    
    var output= data.cbfunc.query.count+ "" + data.cbfunc.query.created;     
    document.getElementById("placeholder").innerHTML=output;    
});  

但我收到一个错误

XMLHttpRequest 无法加载 file:///home/shivratna/Desktop/myjson.json。 Access-Control-Allow-Origin 不允许 Origin null。

请帮忙。

衷心感谢

【问题讨论】:

  • 尝试放置 alert("data :"+JSON.stringify(data));也许您正在获取数据。通过放置此行进行验证。
  • bfunc(...) 不是有效的 JSON。它甚至不是有效的 JSONP。
  • 它甚至不是有效的 JSONP。你缺少右括号。
  • 使用 alert() 进行测试,但您似乎有 4 个“{”但只有 1 个“}”
  • @EmRa228 console.log() 更好

标签: javascript jquery json parsing


【解决方案1】:

这不是有效的 JSON。阅读 json.org 了解 JSON 的正确结构。你所拥有的是 JSONP。首先,检查您的 JSON,因为它们没有正确关闭。你缺少右括号。

要将其转换为有效的 JSON,请删除填充函数,如下所示:

{   
  "query": {   
    "count": 1,   
    "created": "2013-05-03T06:20:01Z",   
    "lang": "en-US",   
    "diagnostics": {   
      "publiclyCallable": "true",   
      "cache": {    
        "execution-start-time": "32",   
        "execution-stop-time": "32",   
        "execution-time": "0",   
        "method": "GET",   
        "type": "MEMCACHED",   
        "content": "http://www.vtualerts.com/robots.txt"   
      }
    }
  }
}

【讨论】:

  • 1"1" 也是有效的 JSON。即使null 也是有效的JSON
  • @JanDvorak 在他的情况下很好,它应该以{} 开头,但无论如何,我会改写。
【解决方案2】:

为什么你用这样的json数据,这是无效的,你可以用json数据这样的

{ "query": {
"count": 1,
"created": "2013-05-03T06:20:01Z",
"lang": "en-US",
"diagnostics": {
    "publiclyCallable": "true",
    "cache": {
        "execution-start-time": "32",
        "execution-stop-time": "32",
        "execution-time": "0",
        "method": "GET",
        "type": "MEMCACHED",
        "content": "http://www.vtualerts.com/robots.txt"
    }
}
}
}

你的最终代码..

    $.getJSON('myjson.json', function(data) {    
      var output= data.query.count+ "" + data.query.created;     
      document.getElementById("placeholder").innerHTML=output;    
   });  

【讨论】:

  • 你确定吗?
  • 感谢大家的帮助。实际上我是从 YQL 控制台获取这个 json 数据的。我不是自己写的。
猜你喜欢
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 2013-02-28
  • 2016-11-29
  • 1970-01-01
  • 2013-07-30
  • 2023-04-01
相关资源
最近更新 更多