2016-02-14 20 views
0

最初我的Json数据与代码一起在一个php文件中解析它。 它们看起来像:如何导入json文件来解析它

main.php

<script> 
var pdatabase= '{ "pobject" : [' + 
'{ "pname":"Pikachu" , "pid":"1" },' + 
'{ "pname":"Squirtle" , "pid":"2" },' + 
'{ "pname":"Justinbieber" , "pid":"3" }]}'; 
</script> 
<script> 
$(function() { 
    ppdatabase = JSON.parse(pdatabase); 
    plenth=ppdatabase.pobject.length; 
    test=console.log(plenth); 
}); 
</script> 

然后我发现这很可怕来管理我的JSON数据。因此,我将Json数据迁移到名为“obdatabase.json”的单独文件中。

obdatabase.json

var pdatabase= '{ "pobject" : [' + 
'{ "pname":"Pikachu" , "pid":"1" },' + 
'{ "pname":"squirtle" , "pid":"2" },' + 
'{ "pname":"Justinbieber" , "pid":"3" }]}'; 

在main.php,删除原来的JSON数据后,我做了两个尝试访问数据并分析它,但失败了。

首先尝试

<script src="obdatabase.json"></script> 

<script> 
$(function() { 
    ppdatabase = JSON.parse(pdatabase); 
    plenth=ppdatabase.pobject.length; 
    test=console.log(plenth); 
}); 
</script> 

第二次尝试

<script> 
$.get('obdatabase.json', function(pdatabase) { 
    ppdatabase = JSON.parse(pdatabase); 
    plenth=ppdatabase.pobject.length; 
    test=console.log(plenth); 
}); 
</script> 

那么,如何解决这一问题?

+0

简单的方法是什么?你的第一个方法,但添加一个'var ppdatabase =你的JSON;'到文件的开头。保存并加载它作为正常的JavaScript文件。 (对未来的评论员 - iam意识到这不是最好的解决方案) – Fuzzyma

+0

不要尝试手动创建json ...不需要它,它很容易出错 – charlietfl

回答

0

定义JSON文件的内容

{ 
    "pobject": [{ 
     "pname": "Pikachu", 
     "pid": "1" 
    }, { 
     "pname": "squirtle", 
     "pid": "2" 
    }, { 
     "pname": "Justinbieber", 
     "pid": "3" 
    }] 
} 

然后使用$.getJSON()直接,无需使用JSON.parse()

$.getJSON('obdatabase.json', function(pdatabase) { 
    plenth=ppdatabase.pobject.length; 
    test=console.log(plenth); 
}); 
0

你混合JSON和JSON像JavaScript对象,JSON能不包含代码,它应该只包含JSON(例如{"foo":"bar"}

你真正想要的是一个obdatabase.js文件ins tead of a obdatabase.json

0

查看链接。 https://jsfiddle.net/bjfu45q4/

var pdatabase= '{ "pobject" : [' + 
'{ "pname":"Pikachu" , "pid":"1" },' + 
'{ "pname":"squirtle" , "pid":"2" },' + 
'{ "pname":"Justinbieber" , "pid":"3" }]}'; 

OR 

var pdatabase = { 
    "pobject" : [ 
     {"pname" : "Pikachu", "pid" : "1"}, 
     {"pname" : "squirtle", "pid" : "2"}, 
     {"pname" : "Justinbieber", "pid" : "3"} 
    ] 
}; 

var tmpJson = JSON.parse(pdatabase); 
console.log(tmpJson.pobject.length); 
0

你并不需要字符串化的数据使用它作为一个变量只是为了然后将其转换到使用JSON.parse

对象如果你只是简单地使用:

var pdatabase = { 
    "pobject" : [ 
     {"pname" : "Pikachu", "pid" : "1"}, 
     {"pname" : "squirtle", "pid" : "2"}, 
     {"pname" : "Justinbieber", "pid" : "3"}] 
}; 

在文件或脚本标记中,您将能够直接访问对象