[英]How to get data in deeply nested JSON (more than 5 layers)
I use a Teleport API . 我使用Teleport API 。 Their JSON data is heavily nested and I'm struggling to get the relevant data. 他们的JSON数据被大量嵌套,因此我正在努力获取相关数据。
The data is as below. 数据如下。 I want to get the data in categories . 我想按类别获取数据。
{
"_embedded": {
"city:search-results": [
{
"_embedded": {
"city:item": {
"_embedded": {
"city:urban_area": {
"_embedded": {
"ua:scores": {
"_links": {
"self": {
"href": "https://api.teleport.org/api/urban_areas/slug:tokyo/scores/"
}
},
"categories": [
{
"color": "#f3c32c",
"name": "Housing",
"score_out_of_10": 5.710999999999999
},
{
"color": "#f3d630",
"name": "Cost of Living",
"score_out_of_10": 3.343
},.....
The code. 编码。 I use React, Redux and Lodash and I tried to iterate the data by map function. 我使用React,Redux和Lodash,并尝试通过map函数迭代数据。
let item;
if(this.props.data) {
item = _.map(this.props.data._embedded.city:search-results._embedded.city:item._embedded.city:urban_area._embedded.ua:scores.categories,
/** This nested props doesn't work **/
data => {
return (
<div>
<h2>{data.name}</h2>
<p>{data.score_out_of_10}</p>
</div>
)
})
Is there a better way to iterate the data in heavily nested JSON data? 有没有更好的方法可以在高度嵌套的JSON数据中迭代数据?
You can't have :
in a JS object property: 你不能有:
在一个JS对象的属性:
const obj = {
"ua:scores": 1000
};
console.log(obj.ua:scores); // Throws an error
console.log(obj['ua:scores']); // returns 1000
You can use lodash _.get
to circumvent that issue and safely get your nested value 您可以使用lodash _.get
规避该问题,并安全地获取嵌套值
const categories = _.get(this.props, 'data._embedded.city:search-results._embedded.city:item._embedded.city:urban_area._embedded.ua:scores.categories', []);
return categories.map(data =>
<div>
<h2>{data.name}</h2>
<p>{data.score_out_of_10}</p>
</div>
);
You seem to have a syntax error in your code as :
is a reserved word. 您的代码中似乎存在语法错误,因为:
是保留字。 You should access your properties this way instead 您应该以这种方式访问属性
this.props.data["_embedded.city:search-results"]
... this.props.data["_embedded.city:search-results"]
...
Side Note : You might want to check if nested properties exist before accessing them in order to avoid the error cannot access property pp of undefined
注意 :您可能想在访问嵌套属性之前检查它们是否存在,以避免错误cannot access property pp of undefined
Since you mentioned lodash try to use the get
utility : 既然您提到lodash,请尝试使用get
实用程序:
import _get from 'lodash/get';
_get(this.props.data, '_embedded.city:search-results._embedded.city:item._embedded.city:urban_area._embedded.ua:scores.categories', ''),
To prevent the use of the reserved keyword :
when you try to access the data, and this helps also to prevent the app from crashing when the data don't exist. 当您尝试访问数据时,可以防止使用reserved关键字:
,这也有助于防止应用程序在不存在数据时崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.