[英]How to import a json file to parse it
最初,我的Json数据与解析它的代码一起存在于php文件中。 他们看着像是:
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>
那么如何解决呢?
将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);
});
您正在javascript中混合使用JSON和JSON对象,JSON不能包含代码,它只能包含JSON(例如{"foo":"bar"}
)
你真正想要的是一个obdatabase.js
文件,而不是obdatabase.json
请参阅链接。 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);
您无需对数据进行字符串化即可将其用作变量,而只需使用JSON.parse
将其转换为对象即可。
如果您只是使用:
var pdatabase = {
"pobject" : [
{"pname" : "Pikachu", "pid" : "1"},
{"pname" : "squirtle", "pid" : "2"},
{"pname" : "Justinbieber", "pid" : "3"}]
};
在文件或脚本标签中,您将可以直接访问对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.