【问题标题】:How can I parse JSON data in Lighthouse?如何在 Lighthouse 中解析 JSON 数据?
【发布时间】:2021-08-03 07:13:53
【问题描述】:

我有通知表,其中数据字段存储为 json :

{"data":{"description":"Event Status has been changed to pending","event_id":19}}

我收到此错误

"errors": [
{
  "debugMessage": "Expected a value of type \"String\" but received: {\"data\":{\"description\":\"Event Status has been changed to pending\",\"event_id\":19}}",

我尝试在通知模型上添加以下内容:

public function getDataAttribute($data)
{
    return json_decode($data, true);
}

但没有解决办法。

我尝试在 GraphQL 架构中使用 [String],但没有。

【问题讨论】:

  • 您试图将对象/数组/记录 - [复杂] graphql 中的单独类型 - 作为单个字符串返回?没办法...使用 自定义 json 标量 stackoverflow.com/a/62647404/6124657 ?

标签: graphql laravel-lighthouse


【解决方案1】:

如果您希望将任意 JSON 数据作为字符串返回,有 2 个选项:

第一种是使用 JSON 标量,您可以自己构建或使用composer package。它会将数据编码为有效的 JSON 字符串。

第二个选项是确保您只返回 JSON 而不是解码的 JSON。我假设您的数据已经解码为 JSON,因为您使用的是 model casts,如果没有,您可以删除 json_decode 调用。您可以添加一个 getter 以将其重新编码回 JSON,或者添加一个 getter 以从模型的 attributes 属性中获取值。

public function getRawDataAttribute(): string
{
    return $this->attributes['data'];
}

// or

public function getRawDataAttribute(): string
{
     return json_encode($this->data);
}

您可以像这样在架构中使用它:

type MyType {
    data: String! @rename(attribute: "raw_data")
}

但在我看来,第一个选项绝对是最简单和最好的,因为它在架构中正确指示该字段包含 JSON 并为您处理编码(以及在输入中使用时的解码)。

【讨论】:

    【解决方案2】:

    将这个用于实现 JSON 类型的包添加到您的应用中:

    https://github.com/mll-lab/graphql-php-scalars

    然后将此行添加到您的schema.graphql 文件中:

    scalar JSON @scalar(class: "MLL\\GraphQLScalars\\JSON")
    

    之后你就可以像这样轻松地使用 JSON 类型了:

    type MyType {
        data: JSON! @rename(attribute: "raw_data")
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-24
      • 2015-04-02
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多