David Carneros
David Carneros

Reputation: 95

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
    }
  }
}

Upvotes: 3

Views: 18435

Answers (4)

dimazx
dimazx

Reputation: 11

There is an online converter:

https://datafetcher.com/graphql-json-body-converter

But if use token address, you need add backslash before double quotes (tested in postman). For example this is graphql query:

{
  pairs(where: {token0: "0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa", token1: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}) {
    token0 {
      name
      symbol
    }
    token0Price
    token1 {
      name
      symbol
    }
    token1Price
  }
}

And this is result of conversion to JSON from previous link:

{
  "query": "{ pairs(where: {token0: "0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa", token1: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"}) { token0 { name symbol } token0Price token1 { name symbol } token1Price }}"
}

Just add backslashes before double quotes near token addresses. Result:

{
  "query": "{ pairs(where: {token0: \"0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa\", token1: \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\"}) { token0 { name symbol } token0Price token1 { name symbol } token1Price }}"
}

Upvotes: 1

Patrick Atoon
Patrick Atoon

Reputation: 769

According to the documentation: to POST a graphQL query to a webservice in a JSON body, simply remove all newlines from the graphQL query, then put it in the following JSON:

{
    "query": "[graphQL query here]",
    "variables": {}
}

In your case, this would look like:

{
    "query": "query { Patient(id:4){ id birthDate { year, day } name { text } } }",
    "variables": {}
}

Upvotes: 0

Daniel Rearden
Daniel Rearden

Reputation: 84667

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)

Upvotes: 3

gbalduzzi
gbalduzzi

Reputation: 10166

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

Upvotes: 1

Related Questions