Skip to content
Advertisement

GitHub GraphQL API Problems parsing JSON

What is wrong here?

JavaScript

I’ve got

JavaScript

but this snippet of code below works correctly

JavaScript

I’ve tried out to change quotes (from ” into ‘ or with ” and so on) but it doesn’t work.

Advertisement

Answer

The problem is related with the double quotes (“). On the first snippet, when you join the '{"query": "'+query+'"}' with the query variable, you get the following result:

JavaScript

Notice how the double quote from "ALEXSSS" are not escaped, therefore the resultant string is not a json valid format.

When you run the second snippet, the resultant string is:

JavaScript

which is a valid json string.

The easiest and best solution is simply use the JSON library instead of trying to do it manually, so you won’t need to worry about escaping characters.

JavaScript

But remember that you could also just escape the characters on the query manually:

JavaScript

it works as expected :)

Advertisement