如何从 json 文件中检索所有字段

How to retrieve all fields from a json file?

本文关键字:检索 字段 文件 json      更新时间:2023-09-26

我想只检索字段名称,而不是它们的值。

我当前的代码是:

    app.get("/api/borough_all_fields", function(req, res){
    // set the type of content in the response
    res.writeHead(200, {'Content-Type': 'application/json'});
    var borFld = null;
    // what to put in here?
    // add the results to an array
    respJson["results"] = [ borFld ];
    res.end( JSON.stringify( respJson ) );
});

另外,如何指定字段名称并返回所有记录的值?例如,指定GSS_code并返回所有值,仅针对 gss 代码及其名称?

您需要传递正确的 json 路径。

var borFld = Object.keys(json.features[0].properties); 

如果数组中有多个对象,则需要在数组上运行 for 循环并传递上述行,它将返回所需的结果。

您可以使用内置对象函数如果你有这样的对象

var jsonObj = {"person":"me","age":"30"};
var borFld = Object.keys(jsonObj);  // returns ["person", "age"]