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.

6
  • 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 minimal reproducible example that shows the problem Commented Nov 8, 2020 at 16:48
  • AppliedPermissions.js:18 Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 Commented Nov 8, 2020 at 16:49
  • What you have is JSON. See: What is the difference between JSON and Object Literal Notation?. You want to parse this into an object. If JSON.parse doesn't work for you, you should supply a minimal reproducible example because your code is correct. Commented Nov 8, 2020 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? Commented Nov 8, 2020 at 16:50
  • @VLAZ because when I am trying to loop through it. It's printing every character of that string. Commented Nov 8, 2020 at 17:01

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.