【问题标题】:How to get the path of a property from a JSON [closed]如何从 JSON 中获取属性的路径 [关闭]
【发布时间】:2021-05-21 12:48:47
【问题描述】:

我遍历一个 JSON,我想找出特定键的路径。

例如我有 JSON:

      `{"address": {
            "city": {
                "type": "string"
            },
            "country": {
                "type": "string"
            },
            "county": {
                "type": "string"
            },
            "street": {
                "car"{
                 "type": "string"
                }
                "type": "string"
            }
         }`

我想获取关键汽车的路径以将其引用到其他地方。

【问题讨论】:

  • 密钥type的路径是什么?您是在寻找第一次、最后一次还是所有发生的事件?
  • 钥匙车的路径,不是类型的。
  • 密钥car的路径是address.street.car
  • 是的,但我想了解如何通过 javascript 函数动态获取它

标签: javascript arrays json typescript


【解决方案1】:

我不建议您编写自己的代码来迭代 JSON(因为您必须维护它,而且您可能会写错,然后其他人将不得不对其进行调试)。

使用库,例如​​flat

然后创建一些小型、易于测试的实用程序函数,从该库中获得您想要的。

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`

// super short and sweet version
const getPathForKey = (json,key) => {
  const flattened = flat(json);
  const found = Object.keys(flattened).find(k => k.match(new RegExp(key));
  return found ? found.replace(new RegExp(`${key}(.*)$`),key) : undefined;
}

是的,我意识到这不是“完美”的,但在 97% 的情况下它是一个“足够好”的解决方案。

【讨论】:

    【解决方案2】:

    首先您需要更正您的 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多