我试图在json文件中获得键的值,但有几个问题我需要解决。
-
JSON的键是动态的-我有另一个JSON,其中我给出了JSON内部键的路径。例如,我有一个json文件,其中包含以下映射:
{"addressesPath"personal.addresses"}
这告诉我,我正在寻找的值在另一个名为personal的键中。JSON看起来像这样:
{
"username": "X1",
"id":"1X",
"type": "patron",
"group": "students",
"personal": {
"lastname": "lname",
"firstname": "fname",
"email": "test@test.test",
"phone": "1-111-111-1111",
"mobilePhone": "(111)111-1111",
"birthDate": "1979-01-23T00:00:00.000+0000",
"addresses":
{
"countryId": "US",
"addressLine1": "1111 Brannon Ford Suite 111",
"city": "Kettering",
"region": "MA",
"postalCode": "11111-1111",
"primaryAddress": true
}
}
}
例如JSON是"user",我想得到的是user。personal。addresses
如何翻译"user.personal.addresses""用户。+ dynamic" ?我试着这样做,但它似乎不与任何类型的字符串我从映射json文件提取工作。
我有一个问题,因为我不知道我得到的位置是单个值还是一个值数组。例如,JSON可以像这样:
{"username"X1"id"1 x"type"patron"group"students"personal" {"lastname"lname"firstname"fname"email"test@test.test"phone"1 - 111 - 111 - 1111","mobilePhone"(111)111 - 1111,,"birthDate"1979 - 01 - 23 t00:00:00.000 + 0000","addresses"({"countryId"US"addressLine1"; "1111 Brannon Ford套房111"city"Kettering"region"MA"postalCode"11111 - 1111","primaryAddress"没错}, {"countryId"US"addressLine1"; "1112 Brannon Ford套房112"city"Kettering"region"IL"postalCode"11112 - 1112","primaryAddress"假的}]}}
这意味着我需要确定我将要获得的数据的结构,无论它是否是数组。我可以通过检查结果是字符串还是对象来做到这一点吗?我知道JSON文件中的数组在node js中被读取为对象。
你想要这样的东西有三个例子
let object = {
"group": "students",
"personal": {
"addresses": {
"countryId": "US",
}
}
}
let test1 = checkObject(object, "personal.addresses")
console.log(test1);
let object2 = {
"test": {
"test_deep": [
{
"countryId": "US",
"addressLine1": "1111 Brannon Ford Suite 111"
},
{
"countryId": "US",
"addressLine1": "1112 Brannon Ford Suite 112",
}
]
}
}
let test2 = checkObject(object2, "test.test_deep")
console.log(test2);
let object3 = {
"test": {
"test_deep": "test"
}
}
let test3 = checkObject(object3, "test.test_deep")
console.log(test3);
function checkObject(object, addressesPath) {
let addres = addressesPath.split(".")
let item = object
for (let index = 0; index < addres.length; index++) {
if (typeof item[addres[index]] != 'undefined') {
item = item[addres[index]]
} else {
item = null
break
}
}
return {
type: typeof item,
is_array: Array.isArray(item),
data: item
}
}