如何导入json文件来解析它

时间:2016-02-14 17:07:06

标签: javascript php jquery html json

最初我的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>

那么如何解决这个问题呢?

4 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:0)

你在javascript中混合JSON和JSON之类的对象,JSON不能包含代码,它应该只包含JSON(例如{"foo":"bar"}

您真正想要的是obdatabase.js文件,而不是obdatabase.json

答案 2 :(得分: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);

答案 3 :(得分:0)

您不需要对该数据进行字符串化以将其用作变量,然后使用JSON.parse将其转换为对象

如果您只是使用:

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

在文件或脚本标签中,您可以直接访问该对象