Skip to content Skip to sidebar Skip to footer

Invalid Json In The ‘operations’ Multipart Field In Formdata In Next Js Application?

I have one mutation like this- mutation signUp($avatar: Upload!) { signUp( avatar: $avatar input: { name: 'Siam Ahnaf' email: 'siamahnaf198@aol.com' pa

Solution 1:

I'm copying my answer here from the almost-duplicate question in case that one gets closed:

If you have quotes inside quotes and you want to run JSON.parse on it, you have to escape them (as others have mentioned). However, in your follow-up duplicate, you can't just single escape the quotes. You have to double- or triple-escape them.

Here's the explanation:

'{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: \"Siam Ahnaf\", email: \"siamahnaf198@yahoo.com\", password: \"siam1980\"}){message, token}}", "variables": { "file": null } }'

When this gets parsed by JavaScript (because it's inside single quotes), it takes the \" and realizes you're trying to escape them (unnecessarily, since it wasn't a single quote), so it converts it into ". Now the parser sees the value inside the quotes (escaped):

{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: "SiamAhnaf", email: "siamahnaf198@yahoo.com", password: "siam1980"}){message, token}}", "variables": { "file": null } }

As you can see, the syntax highlighter changes colors halfway through, because the quotes were already escaped.

To get the desired output, you have to make the FIRST string processing end up with backslashes in it, so you have to escape THE BACKSLASHES too:

'{ "query": "mutation($file: Upload!) {signUp(avatar: $file, input: {name: \\"Siam Ahnaf\\", email: \\"siamahnaf198@yahoo.com\\", password: \\"siam198\\"}){message, token}}", "variables": { "file": null } }'

Now the question is if you need TWO backslashes or THREE. The answer here is that since your OUTER string uses single quotes, you don't need to ALSO escape the double quotes inside, so you only need two backslashes for every double quote you want to keep. If you were using double quotes for your outer string, you'd have to triple escape instead of just double, or your quote wouldn't also get escaped, and the original string would be invalid.

Rule of thumb: if you're trying to escape the SAME type of quote you're using for your string, triple escape. If you're trying to escape a different type, double escape.

Post a Comment for "Invalid Json In The ‘operations’ Multipart Field In Formdata In Next Js Application?"