【问题标题】:How to remove brakets on Json respone如何删除 Json 响应中的括号
【发布时间】:2019-11-01 04:58:39
【问题描述】:

我正在使用 passeport 开发 Laravel Rest Api, 作为回报 response()->json() 我想修剪括号

我尝试了 trim($json,'[]') 函数,但这不是我想要的

public function getOffers()
    {
        $offers = Offer::where('type', 'primary')->where('active', 1)->get();
        $paks = Offer::where('type', 'pack')->where('active', 1)->get();
        return response()->json([
            'offersList' => $offers,
            'packsList' => $paks,
        ], 200);

    }

我希望输出是

{
    "offersList": {
        {
            "id": 3,
            "name": "Gold",
            "description": null
        }
    },
    "packsList":[]
}

但实际结果是

{
    "offersList": [
        {
            "id": 3,
            "name": "Gold",
            "description": null
        }
    ],
    "packsList":[]
}

【问题讨论】:

  • 为什么不想要 [] 括号?它们是您在此处所做操作的正确符号。
  • 仅供参考,您的“预期”输出无效。 Expecting 'STRING', '}', got '{'

标签: json laravel api response laravel-passport


【解决方案1】:

$offers 是一个集合,因此是 JSON 中的一个数组。

如果 $offers 应该是单个项目,请使用 first() 而不是 get(),它将在 JSON 中呈现为单个对象而不是对象数组。

$offers = Offer::where('type', 'primary')->where('active', 1)->first();

如果$offers 有时应该包含多个 报价,请保持原样;没错!

【讨论】:

    【解决方案2】:

    嵌套在另一个对象中的大括号 {} 不是有效的 JSON。

    对象可用于属性值和数组元素。

    无效的 JSON

    {
      "offersList": {
        {
          "id": 3,
          "name": "Gold",
          "description": null
        }
      }
    }
    

    有效选项 1

    {
      "offersList": [
        {
          "id": 3,
          "name": "Gold",
          "description": null
        }
      ]
    }
    

    有效的选项 2

    {
      "offersList": {
        "id": 3,
        "name": "Gold",
        "description": null
      }
    }
    

    您可以使用在线 linter 快速验证您的 JSON 结构。 https://jsonformatter.curiousconcept.com/

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多