使用Javascript和jQuery解析JSON

问题描述:

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数据。我试图做这样的......使用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无法加载文件:///home/shivratna/Desktop/myjson.json。 Access-Control-Allow-Origin不允许Origin null。

请大家帮忙。

真诚的感谢

+0

URL正确吗? – 2013-05-03 07:04:44

+0

尝试放置警报(“data:”+ JSON.stringify(data));也许你正在获取数据。通过放置这条线进行验证。 – Anil 2013-05-03 07:05:08

+4

'bfunc(...)'不是有效的JSON。这甚至不是有效的JSONP。 – 2013-05-03 07:05:50

这不是有效的JSON。请阅读json.org了解JSON的正确结构。你有什么是JSONP。在别的之前,请检查您的JSON,因为它们没有正确关闭。你缺少大括号。

把它变成有效的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'和'“1”'也是有效的JSON。即使'null'也是有效的JSON – 2013-05-03 07:11:53

+0

@JanDvorak在他的情况下,它应该以'{}'开始,但无论如何,我会重述。 – Joseph 2013-05-03 07:12:51

,这是无效的,你可以使用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;  
    }); 
+3

你确定吗? – Joseph 2013-05-03 07:15:35

+0

关于json数据? – praveen 2013-05-03 07:22:15

+0

Thnax每个人都为你提供帮助。其实我从YQL控制台获取这个json数据。我不是自己写的。 – 2013-05-03 07:27:41