如何导入 json 文件来解析它


How to import a json file to parse it

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

主.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" }]}';

在主要.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

您无需将该数据字符串化即可将其用作变量,只需使用JSON.parse将其转换为对象

如果您只是使用:

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

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

请参阅链接。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);