JSON 响应处理问题


json response handling issue

我坚持检索 json 响应 下面是 json 输出。您的帮助将不胜感激。

{ "productHeader" : { "totalHits" : 684 }, "products" : [ { "name" : "Victoria Hotels", "productImage" : { "url" : "http://hotels.com/hotels/9000000/8640000/8633700/8633672/8633672_20_b.jpg" }, "language" : "en", "description" : "Location. Victoria Hotels is in Foshan (Nanhai) and area attractions include Renshou Temple and New Plaza Stadium. Additional regional attractions include Guangdong Folk Art Museum and Bright Filial Piety Temple.", "identifiers" : { }, "fields" : [ { "name" : "regions2", "value" : "Guangdong" }, 

请帮助我获取特定值。例如,如果我需要从 json 响应中获取名称、图像 url。

您可以使用

json_decode将 JSON 字符串解析为数组并访问其值:

// assuming, that $string contains the json response
// second parameter to true, to get an array instead of an object
$data = json_decode( $string, true );
if ( $data ) {
  echo $data['products'][0]['name'];
  // or whatever value
} else {
  echo 'JSON could not be parsed, error: ' . json_last_error();
}

要显示 product 数组中的所有值,只需循环它:

if ( $data ) {
  foreach($data['products'] as $product){
      echo $product['name'];
  }
  // or whatever value
} else {...

如果你打算使用 PHP 来获取值,请检查这个:

$decodedJson = json_decode($json, true);
print_r($decodedJson);

您将获得一个数组,要获取图像源和其他标签,您需要循环或选择具体的索引,例如:

echo $decodedJson['productHeader']['products'][0]['productImage']['url'];

在JS中,您应该以相同的方式提取值。