It seems like this should work:
import graphene
from graphene.types.json import JSONString
class CreatePerson(graphene.Mutation):
class Input:
name = graphene.String()
data = JSONString()
ok = graphene.Boolean()
person = graphene.Field(lambda: Person)
@staticmethod
def mutate(root, args, context, info):
person = Person(name=args.get('name'), data=args.get('data'))
ok = True
return CreatePerson(person=person, ok=ok)
class Person(graphene.ObjectType):
name = graphene.String()
age = graphene.Int()
data = JSONString()
class MyMutations(graphene.ObjectType):
create_person = CreatePerson.Field()
# We must define a query for our schema
class Query(graphene.ObjectType):
person = graphene.Field(Person)
schema = graphene.Schema(query=Query, mutation=MyMutations)
res = schema.execute("""
mutation myFirstMutation {
createPerson(name:"Peter", data: "{\"foo\":\"bar\"}") {
person {
name,
data
}
ok
}
}""")
print(res.errors)
print(res.data)
But it gives this error:
[GraphQLSyntaxError('Syntax Error GraphQL request (3:45) Expected :, found String ":"\n\n2: mutation myFirstMutation {\n3: createPerson(name:"Peter", data: "{"foo":"bar"}") {\n ^\n4: person {\n',)]
If I change the argument to an empty JSON object (ie "{}"), then I don't get the error anymore.
Judging by issue #223, this worked as of July 2016.
I've found that this works if I use double backslashes to escape the quotes in the mutation argument. Working example:
import graphene
from pprint import pprint
class CreatePerson(graphene.Mutation):
class Arguments:
name = graphene.String()
meta = graphene.JSONString()
ok = graphene.Boolean()
person = graphene.Field(lambda: Person)
def mutate(self, info, name, meta):
pprint(meta)
person = Person(name=name, meta=meta)
ok = True
return CreatePerson(person=person, ok=ok)
class Person(graphene.ObjectType):
name = graphene.String()
meta = graphene.JSONString()
class MyMutations(graphene.ObjectType):
create_person = CreatePerson.Field()
# We must define a query for our schema
class Query(graphene.ObjectType):
person = graphene.Field(Person)
schema = graphene.Schema(query=Query, mutation=MyMutations)
q = """
mutation myFirstMutation {
createPerson(name:"Peter", meta:"{\\"foo\\":\\"bar\\"}") {
person {
name,
meta
}
ok
}
}
"""
result = schema.execute(q)
print(result)
print(result.errors)
import json
print(json.dumps(result.data, indent=2))
Most helpful comment
I've found that this works if I use double backslashes to escape the quotes in the mutation argument. Working example: