0

I am trying to parse a String response from an API to JSON in ReactJS.

My string response looks like this:

[{"fromArea":"chocolate","toArea":"chocolate","distance":"100"},{"fromArea":"strawberry","toArea":"strawberry","distance":"200"},{"fromArea":"vanilla","toArea":"vanilla","distance":"300"}]

So far, I have tried:

JSON.parse(element.permission))

JSON.parse("\'"+element.permission+"\'")

I am getting error as:

AppliedPermissions.js:18 Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1

Referred from:

Convert string array to array in javascript

Any help would be constructive.

  • Are you getting any errors? What is `parse()`returning if it isnt throwing errors? How are you retrieving the response? Is it maybe already parsed, as libraries like `jQuery` will do? Provide a [mcve] that shows the problem – Patrick Evans Nov 08 '20 at 16:48
  • `AppliedPermissions.js:18 Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1` – VIVANK SHARMA 17BIT0325 Nov 08 '20 at 16:49
  • What you have ***is JSON***. See: [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/q/2904131). You want to parse this *into an object*. If `JSON.parse` doesn't work for you, you should supply a [mcve] because your code is correct. – VLAZ Nov 08 '20 at 16:50
  • 1
    If you're getting `Unexpected token o in JSON at position 1` you *most likely* already have an object. Why do you think you need to parse it? – VLAZ Nov 08 '20 at 16:50
  • @VLAZ because when I am trying to loop through it. It's printing every character of that string. – VIVANK SHARMA 17BIT0325 Nov 08 '20 at 17:01
  • Then either your loop is wrong or what you're showing is here is wrong. There is no way for you to be getting this error with the data you've provided. And if you do have the data provided, then looping shouldn't be printing every character. We need a [mcve] because as it stands, it's not possible to say what exactly is wrong. – VLAZ Nov 08 '20 at 17:03

2 Answers2

0

AppliedPermissions.js:18 Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1.

this means that what you are sending in JSON.parse() is already an object.
So what you say is a string representation is already an object and most likely is the JSON that you are trying to get, precisely is an array of json objects.

Ismail Diari
  • 498
  • 3
  • 8
-1
let json = {};
const paramRegex = /"[a-zA-Z0-9]":/;
const attrRegex = /:"[a-zA-Z0-9]"/;
const params = [];
const attrs = [];

while((param = paramRegex.exec(element.permission)) !== null) {
    params.push(param);
}

while((attr = attrRegex.exec(element.permission)) !== null) {
    attrs.push(attr);
}

let i = 0;
while (i < params.length && i < attrs.length) {
    json[params[i]] = attrs[i];
    i++;
}
k-wasilewski
  • 3,943
  • 4
  • 12
  • 29