Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I transform a query graphql to a json object?

I have a problem and I need to transform a query graphql to a json object. That is, I get a query in the following way and I would like to have a json of that query. How could I do it? I've been searching and I haven't found a way.

Thank you.

query {
  Patient(id:4){
    id
    birthDate {
      year,
      day
    }
    name {
      text
    }
  }
}
like image 983
David Carneros Avatar asked Oct 16 '25 11:10

David Carneros


2 Answers

Any GraphQL document, whether it's a query or a schema, can be represented as an AST object. This is the standard way to represent a GraphQL document as an object. You can parse a document string into an object using the core library:

const { parse } = require('graphql')
const object = parse(`
  query {
    # ...
  }
`)

The object can be converted back into a string as well:

const { print } = require('graphql')
const string = print(object)
like image 152
Daniel Rearden Avatar answered Oct 19 '25 02:10

Daniel Rearden


GraphQL does not define a JSON standard for queries.

If you want to express a graphQL in JSON, you can define your own structure and write your own serializers. but it will not be supported by any graphQL service

EDIT: I found an NPM package that does that. It is not a standard whatsoever, but if you really need it, you can use this package: https://www.npmjs.com/package/json-to-graphql-query

like image 40
gbalduzzi Avatar answered Oct 19 '25 02:10

gbalduzzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!