graphql icon indicating copy to clipboard operation
graphql copied to clipboard

Programmatically query json object

Open tamalsaha opened this issue 3 years ago • 3 comments

Is it possible to write a function that can return the projection of a json object via GraphQL query?

func project(doc map[string]interface{}, query string) -> returns the output?

tamalsaha avatar Jul 31 '20 07:07 tamalsaha

Hi @tamalsaha, thanks for looking into the lib.

Could you expand on return the projection of a json object, could you provide an example of the query your planning to use and the output that you would expect ?

chris-ramon avatar Aug 01 '20 07:08 chris-ramon

Thanks, @chris-ramon ! Here is an example:

Input

{
  "apiVersion": "apps/v1",
  "kind": "Deployment",
  "metadata": {
    "name": "busy-dep",
    "labels": {
      "app": "busy-dep"
    }
  },
  "spec": {
    "replicas": 1,
    "selector": {
      "matchLabels": {
        "app": "busy-dep"
      }
    },
    "template": {
      "metadata": {
        "labels": {
          "app": "busy-dep"
        }
      },
      "spec": {
        "containers": [
          {
            "image": "busybox",
            "command": [
              "sleep",
              "3600"
            ],
            "imagePullPolicy": "IfNotPresent",
            "name": "busybox"
          },
          {
            "image": "ubuntu:18.04",
            "command": [
              "sleep",
              "3600"
            ],
            "imagePullPolicy": "IfNotPresent",
            "name": "ubuntu"
          }
        ],
        "restartPolicy": "Always"
      }
    }
  }
}

Query

query {
	apiVersion
	kind
	metdata {
		name
	}
	spec {
		replicas
	}
}

Output

{
  "apiVersion": "apps/v1",
  "kind": "Deployment",
  "metadata": {
    "name": "busy-dep",
  },
  "spec": {
    "replicas": 1
  }
}

I want to use GraphQL query syntax on nested JSON doc. Is this possible?

tamalsaha avatar Aug 01 '20 07:08 tamalsaha

graphql can only query fields defined in the object so you cannot add dynamic/undefined fields to a query. You do however have a few options

  1. if the data in the json blob is completely dynamic you can use a custom JSON type for the field and a directive that is able to search the field and display only the things you want displayed. This is a fair amount of custom code you would need to generate
  2. if the json structure is one of a known set of structures you can use an interface or union and define each object type

bhoriuchi avatar Aug 06 '20 16:08 bhoriuchi