Javascript 如何从JSON获取属性的路径
我迭代一个JSON,我想知道一个特定键的路径是什么 例如,我有JSON:Javascript 如何从JSON获取属性的路径,javascript,arrays,json,typescript,Javascript,Arrays,Json,Typescript,我迭代一个JSON,我想知道一个特定键的路径是什么 例如,我有JSON: `{"address": { "city": { "type": "string" }, "country": { "type": "string&
`{"address": {
"city": {
"type": "string"
},
"country": {
"type": "string"
},
"county": {
"type": "string"
},
"street": {
"car"{
"type": "string"
}
"type": "string"
}
}`
我想得到key car在其他地方引用它的路径。首先需要更正JSON,因为它是无效的。然后需要解析。然后迭代如下
let myObj = `{
"address": {
"city": {
"type": "string"
},
"country": {
"type": "string"
},
"county": {
"type": "string"
},
"street": {
"car": {
"type": "string"
},
"type": "string"
}
}
}`
myObj = JSON.parse(myObj)
const path = []
let pathFound = false
findPath(myObj, 'car')
function findPath (obj, objKey) {
for (const key in obj) {
if (key === objKey) {
pathFound = true
return path.push(key)
}
if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
path.push(key)
findPath(obj[key], objKey)
}
}
if (!pathFound) {
path.pop()
}
}
console.log(path)
我不建议您编写自己的代码来迭代JSON(因为这样您就必须维护它,您可能会写错,然后其他人将不得不调试它) 使用库,例如 然后创建一些小的、易于测试的实用程序函数,从库中获取所需的内容
import flat from 'flat';
const yourJson = {
"address": {
"city": {
"type": "string"
},
"country": {
"type": "string"
},
"county": {
"type": "string"
},
"street": {
"car": {
"type": "string"
},
"type": "string"
}
}
}
const getPath = (json,matcher,transform) => {
const flattened = flat(json);
return transform(Object.keys(flattened).find(matcher));
}
// use it like this
console.log(
getPath(
yourJson, // your json
(key) => key.match(/car/), // a matcher function that matches a specific key - in this case, the key must end in `car`
key => key?.replace(/car(.*)$/,'car') // strip everything after the path that you matched, that you aren't interested in
)
); // logs `address.street.car`
//超短甜美版
const getPathForKey=(json,键)=>{
常数平坦=平坦(json);
const found=Object.keys(展平).find(k=>k.match(new RegExp(key));
return found?found.replace(new RegExp(`${key}(.*$`)),key:未定义;
}
是的,我意识到这不是“性能”完美,但它是“足够好”97%情况下的解决方案。key
type
的路径是什么?您是在查找第一次、最后一次还是所有发生的情况?key car的路径,而不是type。keycar
的路径是address.street.car
。是的,但我想知道如何通过javascript函数动态获取它,您的意思是:?