【问题标题】:JSON, unable to decode in laravelJSON,无法在laravel中解码
【发布时间】:2019-06-08 20:24:27
【问题描述】:

我目前正在转储对返回 JSON 数据的 API 的调用:

<?php dd($info)?>

哪些转储

{#39751 ▼
+"categories": array:19 [▼
0 => {#1065 ▼
  +"category_name": "Block"
  +"category_description": "Description details"
  +"products": array:24 [▼
    0 => {#1070 ▼
      +"price": {
      "01":"100.00"
      }
      +"product_info": {
        "product_code": 123,
        "product_type":{
            "quantity": 2
        }
      }
    }
    1 => {#1070 ▼
      +"price": {
      "01":"200.00"
      }
      +"product_info": {
        "product_code": 112,
        "product_type":{
            "quantity": 3
        }
      }
    }
1 => {#1065 ▼
  +"category_name": "Flat"
  +"category_description": "Description details"
  +"products": array:24 [▼
    0 => {#1070 ▼
      +"price": {
      "01":"100.00"
      }
      +"product_info": {
        "product_code": 221,
        "product_type":{
            "quantity": 2
        }
      }
    }
    1 => {#1070 ▼
      +"price": {
      "01":"200.00"
      }
      +"product_info": {
        "product_code": 223,
        "product_type":{
            "quantity": 3
        }
      }
    }

但是当我这样做时:

dd(json_decode($info))

它只是返回 null,我似乎无法访问它。

我可以转储这个但不能在刀片中解码它有明显的原因吗?

更新:

最初尝试通过循环/访问来测试:

foreach($info as $info->categories) { 
  $category_name = $info->categories['category_name']; 
  dd($category_name);
}

【问题讨论】:

  • 检查json解码是否失败json_last_error_msg
  • 您的第一个dd() 显示它是 编码的。你为什么要解码它?
  • @Dharman 说它解析失败
  • @Sammitch 我试图循环访问它但不能,所以我认为我需要对其进行解码。我将如何正确循环/访问其中的元素?
  • 发布您遇到问题的代码。

标签: php json laravel


【解决方案1】:
foreach($info as $info->categories) { 
    $category_name = $info->categories['category_name']; 
    dd($category_name);
}

转而去

foreach($info->categories as $category) {
    $category_name = $category['category_name']; 
    dd($category_name);
}

Laravel 是一个框架,可帮助您处理 Web 应用程序的常见请求/响应生命周期。这样做,它通常处理对象的序列化和反序列化以及请求有效负载本身(如果可能)。因此,如果它接收到 JSON 编码的有效负载,它会将其转换为数组,或者如果您愿意,它甚至可以从数组中创建对象,例如您从任何 API 发布一个 json 编码数据,并希望将其转换为您的 Category 实体。最好的做法是顺便说一句。使用 DTO 在用于层间通信的数据和实际持久化的业务对象之间构建一个层。

传递一个对象,例如您将模型/实体分类到视图中,您只需将其按原样分配即可。

请注意,刀片是在服务器上处理的,它在 PHP 中运行,因此根本不需要解码/编码。只有一种情况是,如果您真的想在前端显示 JSON 的表示。

请注意 dd 代表转储和死亡,因此应用程序不会继续。

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 2015-08-28
    • 2018-12-18
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多