Skip to content
Advertisement

String cannot be converted into JSON in Javascript

self.str = "
{"queryString":"user=test&password=1 OR TRUE ; -- ' OR TRUE; -- OR TRUE; K2FUZZ " OR TRUE; -- OR TRUE; K2FUZZ '","clientIP":"127.0.0.1","clientPort":"43470","dataTruncated":false,"contentType":"","requestURI":"/DemoApplication-0.0.1-SNAPSHOT/UserCheck3","generationTime":0,"body":"","method":"GET","url":"/DemoApplication-0.0.1-SNAPSHOT/UserCheck3?user=test&password=test123"}
"

self.obj = JSON.parse(self.str);

I am getting error:

base.js:1 SyntaxError: Unexpected token O in JSON at position 82 at JSON.parse ()

I tried various methods but nothing works. Can anyone tell me why this error is occurring and how can I fix it?

Just for the context, self.str contains a string value that I have obtained from an API response.

Advertisement

Answer

If you work on this backwards – by creating an object and stringifying it – you can see that the quotes in queryString need to be escaped. You can then turn it into valid JSON.

So, whatever data this JSON is coming from needs to be properly formatted because it’s not valid JSON at the moment.

const obj = {
  "queryString": "user=test&password=1 OR TRUE ; -- ' OR TRUE; -- OR TRUE; K2FUZZ "OR TRUE;--OR TRUE;K2FUZZ'",
  "clientIP": "127.0.0.1",
  "clientPort": "43470",
  "dataTruncated": false,
  "contentType": "",
  "requestURI": "/DemoApplication-0.0.1-SNAPSHOT/UserCheck3",
  "generationTime": 0,
  "body": "",
  "method": "GET",
  "url": "/DemoApplication-0.0.1-SNAPSHOT/UserCheck3?user=test&password=test123"
}

const str = JSON.stringify(obj);

document.querySelector('pre').textContent = JSON.stringify(obj, null, 2);

// console.log(JSON.parse(str));
<pre></pre>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement