Skip to content

Navigation Menu

Sign in
Sign up

Is there something like JSON scalar type ? #882

Answered by Vincz
scion4581 asked this question in Q&A
Discussion options

Hello!
In some cases, a response could have an unknown count of fields and even nested ones.
Is there something like JSON scalar type?
Thanks

You must be logged in to vote

Hi. It's quite easy to make your own.
Here is an example with attributes:

<?php
declare(strict_types=1);
namespace App\GraphQL\Scalar;
use GraphQL\Language\AST\BooleanValueNode;
use GraphQL\Language\AST\FloatValueNode;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\ListValueNode;
use GraphQL\Language\AST\ObjectValueNode;
use GraphQL\Language\AST\StringValueNode;
use Overblog\GraphQLBundle\Annotation as GQL;
#[GQL\Scalar]
#[GQL\Description('Json scalar type')]
class Json
{
 public static function serialize($value)
 {
 return $value;
 }
 public static function parseValue($value)
 {
 return $value;
 }
 public static function parseLiteral

Replies: 1 comment

Comment options

Hi. It's quite easy to make your own.
Here is an example with attributes:

<?php
declare(strict_types=1);
namespace App\GraphQL\Scalar;
use GraphQL\Language\AST\BooleanValueNode;
use GraphQL\Language\AST\FloatValueNode;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\ListValueNode;
use GraphQL\Language\AST\ObjectValueNode;
use GraphQL\Language\AST\StringValueNode;
use Overblog\GraphQLBundle\Annotation as GQL;
#[GQL\Scalar]
#[GQL\Description('Json scalar type')]
class Json
{
 public static function serialize($value)
 {
 return $value;
 }
 public static function parseValue($value)
 {
 return $value;
 }
 public static function parseLiteral($valueNode)
 {
 switch ($valueNode) {
 case $valueNode instanceof StringValueNode:
 case $valueNode instanceof BooleanValueNode:
 return $valueNode->value;
 case $valueNode instanceof IntValueNode:
 case $valueNode instanceof FloatValueNode:
 return \floatval($valueNode->value);
 case $valueNode instanceof ObjectValueNode:
 $value = [];
 foreach ($valueNode->fields as $field) {
 $value[$field->name->value] = self::parseLiteral($field->value);
 }
 return $value;
 case $valueNode instanceof ListValueNode:
 return \array_map([self, 'parseLiteral'], $valueNode->values);
 default:
 return null;
 }
 }
}
You must be logged in to vote
0 replies
Answer selected by scion4581
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /