【发布时间】:2021-10-22 17:56:56
【问题描述】:
我从 API URL 获得了一个 REST API 响应。但是我需要将响应的某些部分从 JSON 解码到 Object.Here is the Response.
在这里你可以看到price和service_timespan这两个东西需要在JSON.parse()中。以便可以使用此值。否则,我不能使用它们。
这是我的代码
{ services.length > 0 && services.map(( service, index ) => (
<tr key={service.id} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{service.service_name}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{service.service_cat_id}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{service.price.base_price.amount}</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{service.service_timespan.duration.length}</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="#" className="text-indigo-600 hover:text-indigo-900">
Edit
</a>
</td>
</tr>
))
}
我收到cannot read property amount of undefined
【问题讨论】:
-
您似乎知道
JSON.parse可以解析 JSON,那么是什么阻止您这样做呢? -
我认为让您感到困惑的是您收到的 JSON 字符串包含值也是 json 字符串的字段。因此,在解析完外部对象之后,这些值仍然是需要分别为
JSON.parsed 的字符串。 -
@rayhatfield 你是对的。当我使用 map 函数时,我还需要 JSON.parse 那些 json 字符串。但我无法得到它