Jsonpath获取子节点数据

时间:2018-03-24 00:13:39

标签: javascript json typescript

我在

下面有一个示例json输入
{    
 "India":{
      "Attributes":{"Time":"2006-05-04T03:22:11.499Z"},
      "ActiveCity":{
           "profile":"Mumbai"
      },
      "CurrentCities":{
           "Mumbai":{"population":"121212121","Area":8},
           "Delhi":{"population":"121212121","Area":8},
           "Lonng":{"population":"121212121","Area":8}
      },
      "FeatureCities":{
           "NewMumbai":{"population":"121212121","Area":8},
           "NewDelhi":{"population":"121212121","Area":8},
           "NewLonng":{"population":"121212121","Area":8}
      }
 }
}

我正在使用typescript来仅用ActiveCity替换currentCities部分,例如我的输出应该是这样的

{    
 "India":{
      "Attributes":{"Time":"2006-05-04T03:22:11.499Z"},
      "ActiveCity":{
           "profile":"Mumbai"
      },
      "CurrentCities":{
           "Mumbai":{"population":"121212121","Area":8}
      },
      "FeatureCities":{
           "NewMumbai":{"population":"121212121","Area":8},
           "NewDelhi":{"population":"121212121","Area":8},
           "NewLonng":{"population":"121212121","Area":8}
      }
 }
}

使用Jsonpath如何在打字稿中实现这一点?有什么建议吗?

1 个答案:

答案 0 :(得分:0)

只需使用以下内容中的当前值访问currentCities中的对象:

 obj.India.CurrentCities[obj.India.ActiveCity.profile]



let obj = {  "India": {    "Attributes": {      "Time": "2006-05-04T03:22:11.499Z"    },    "ActiveCity": {      "profile": "Mumbai"    },    "CurrentCities": {      "Mumbai": {        "population": "121212121",        "Area": 8      },      "Delhi": {        "population": "121212121",        "Area": 8      },      "Lonng": {        "population": "121212121",        "Area": 8      }    },    "FeatureCities": {      "NewMumbai": {        "population": "121212121",        "Area": 8      },      "NewDelhi": {        "population": "121212121",        "Area": 8      },      "NewLonng": {        "population": "121212121",        "Area": 8      }    }  }}

obj.India.CurrentCities = {[obj.India.ActiveCity.profile]: obj.India.CurrentCities[obj.India.ActiveCity.profile]}

console.log(obj);

.as-console-wrapper { max-height: 100% !important; top: 0; }