Javascript / JSON-解析存储在外部文件

时间:2018-05-14 04:56:49

标签: javascript json

我有一个包含这些对象的JSON文件 -

{"boys": [
        {"firstName": "George", "lastName": "Kristoferson", "email": "george@gmail.com", "sex": "male"},
        {"firstName": "Bill", "lastName": "Madison", "email": "bill@gmail.com", "sex": "male"},

    ],
"girls": [
        {"firstName": "Anna", "lastName": "Calixtus", "email": "anna@gmail.com", "sex": "female"},
        {"firstName": "Marie", "lastName": "Curie", "email": "marie@gmail.com", "sex": "female},
    ]

}

我写了这一行来获取密钥 -

var people = require("./people.json"); 

但是,这只会存储"男孩"进入变量" people"。 我怎样才能存储"女孩"从JSON到变量呢?

2 个答案:

答案 0 :(得分:0)

第1步:使用myjson.com获取JSON数据的json链接。

enter image description here

生成的JSON网址: https://api.myjson.com/bins/l4rfa

第2步:使用JQuery .getJSON函数从URL中获取数据:

var url = "https://api.myjson.com/bins/l4rfa";

$.getJSON(url, function (data) {
    
    var boys = data.boys;
    var girls = data.girls;
    
    console.log("Boys", boys);
    console.log("Girls", girls);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:-1)

a)您的JSON无效,最后一行缺少双引号

b)你忘记了

module.exports = 
    // your JSON