如何将查询graphql转换为json对象?

问题描述:

我有一个问题,我需要将查询graphql转换为json对象.也就是说,我以以下方式获取查询,并且我希望获得该查询的json.我该怎么办?我一直在搜索,但没有找到方法.

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.

谢谢.

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

任何GraphQL文档,无论是查询还是架构,都可以表示为AST对象.这是将GraphQL文档表示为对象的标准方法.您可以使用核心库将文档字符串解析为对象:

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)