Escaping special characters in JSON queries

When performing a mutation on a media, I get an error when inserting special characters such as new lines \n or tabs \t.

graphql.error.syntax_error.GraphQLSyntaxError: Syntax Error GraphQL request (7:481) Expected Name, found String " add bad characters "

Putting two escapes \\n does not help.

What is the right way to insert them?

Exemple query:

mutation { updateProjectMedia( input: { project_id: 1, clientMutationId: "1", id: "mediaIdnumber==\\n", metadata: "{\\"description\\": \\" Updated Description line 1 \n Description second line! \\" }" }) { project_media { title description id } } }

Hi Marc,

mutation { updateProjectMedia( input: { project_id: 1, clientMutationId: "1", id: "mediaIdnumber==\\n", metadata: "{\\"description\\": \\" Updated Description line 1 \n Description second line! \\" }" }) { project_media { title description id } } }

On metadata, the quotes should be escaped with only one backslash (\") and the newline with two (\\n)

I tested the query below (changing the id only) and the description was updated with the new lines:

mutation {
  updateProjectMedia(input: {
    clientMutationId: "1",
    id: "mediaIdnumber==\\n", 
    metadata: "{\"description\": \" Updated Description line 1 \\n Description second line! \" }"
  }) {
    project_media {
      title
      description
      id
    }
  }
}

Thank you!

The problem came from graphql-python , which escaped the double escape

It can be solved with something like this:

from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
import demoji

gql_transport=RequestsHTTPTransport(
    url='https://check-api.checkmedia.org/api/graphql',
    headers={'Content-Type': 'application/json', 'X-Check-Token': 'secret_token'},
)


gql_client = Client(
    transport=gql_transport,
    fetch_schema_from_transport=True, # increases loading time
)

updated_description = 'My new description \\n On several lines and 🤔emoji...  '

# query string and replace with query parameter values. Because of the curly brackets in the json, we can't use the usual string.format() 

query_string = '''
    mutation {
      updateProjectMedia( input: {
        project_id: %s,
        clientMutationId: "1",
        id: "%s==\\n",
        metadata: "{\\"description\\": \\"%s\\"}"
      }) {
        project_media {
          title
          description
          id
        }
      }
    }
'''% (list_dbid, media_id, updated_description)

    gql_query = gql(query_string)
        # locate the metadata argument in the qgl_query object and edit the string inplace
        gql_query_fields = gql_query.definitions[0].selection_set.selections[0].arguments[0].value.fields
        for gql_field in gql_query_fields:
            if gql_field.name.value == 'metadata':
                # gql_field.value.value is the target string of value:
                # '{"description": "My new description \n On several lines and 🤔emoji... "}'
                # notice that double escape on \n has been escaped by gql_query and needs to be added again
                gql_field.value.value = gql_field.value.value.replace('\n', '\\n')
                gql_field.value.value = gql_field.value.value.replace('\t', '\\t')
                gql_field.value.value = gql_field.value.value.replace('\s', '\\s')
                # line below attempts to escape emojis but yields [TypeError: Object of type 'bytes' is not JSON serializable] when query is executed
                # gql_field.value.value = gql_field.value.value.encode('unicode-escape')
                # As workaround excepttions, delete emojis 
                gql_field.value.value = demoji.replace(gql_field.value.value, '') # TODO escape emojis instead of deleting
    response = gql_client.execute(gql_query)

When emojis are left as such in the description response = gql_client.execute(gql_query)
will return *** Exception: {'message': 'no "data" or "errors" in response from origin'}

Just like \n it seems that they need to be escaped, but encoding(‘unicode-escape’) does not work on JSON types

So I have I have to delete emojis for now. Alternatives for how to handle them are welcome!

1 Like