Search code examples
jsongraphqlapollo-servermutationgraphiql

Inserting a large stringed JSON as an input to a mutation GRAPHQL


I get a large stringified JSON from the client. I would like to use this JSON in order to create items in my DB. I have a mutation that gets this Json as a string. Inside the mutation I parse the json and than use it to fill out my DB. I get an error when I try to run to mutation in Graphiql.

I get a lot of errors: enter image description here

This string is a normal JSON string that I get from the client when using JSON.stringify(obj)


Solution

  • GraphQL deliminates string literals using double quotation marks ("). If you need to use a string literal with one or more double quotation mark characters inside it, you need to correctly escape those characters by inserting a backslash (\) before each one. If you don't do this, GraphQL treats the double quotation mark inside the string as the terminator for the entire string, and normally the next character in your string ends up creating a syntax error.

    So a string value like this:

    {"key": "value"}
    

    needs to be escaped like this:

    {\"key\": \"value\"}
    

    as a literal inside your GraphQL document, it ends up looking like this:

    "{\"key\": \"value\"}"
    

    The same rule also applies to strings you send as variables, but this is due to JSON syntax rules, not GraphQL ones. You can read up more about escaping characters inside strings in the spec.