繁体   English   中英

在NodeJs的console.log中打印JSONPath和值

[英]Print the JSONPath & value in console.log in NodeJs

我想在控制台中打印JSON路径,示例

customer = {  
             "Name" : "Joe",
             "Address" : {
                          "Street" : "SomeStreet",
                          "City"   : "SomeCity"
                          }
            }

myfunction = function(myPath){
    console.log(myPath);
}

myfunction(customer.Address.City);
//This function should print "customer.Address.City" ( Not value "SomeCity")

您可以使用json路径获取值,在下面的简单代码段下找到可以解决您问题的代码,尽管未在所有情况下进行测试。

const myfunction = function (myPath, customer) {
    const value = myPath.split(".").reduce((acc, cur) => {
        return acc[cur]
    }, customer)
    console.log('Path: ', myPath, ' Value: ', value)
}

const customer = {
    "Name": "Joe",
    "Address": {
        "Street": "SomeStreet",
        "City": "SomeCity"
    }
}
myfunction("Address.City", customer)

这里要注意的一件事是,您不应该在json路径中添加变量名,这就是为什么我从json路径中跳过客户的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM