-2

so here is the problem : I am passing a list/array of objects from front end to my node js back end.

This is how it looks on the front end : [{"sample1": "this", "apple2" : eat},{"sample2": "thisIs2", "apple3" : eatFruits}]

but when it is passed to the backend , its converted to String,something like this:
"[{"sample1": "this", "apple2" : eat},{"sample2": "thisIs2", "apple3" : eatFruits}]"

So when I run a for loop in my node js, the length is calculated as each characters. what do i do to get the pure array and the contents in the array. Thanks

11
  • 3
    Does this answer your question? Converting a string to JSON object Commented Oct 26, 2022 at 11:26
  • 1
    Use JSON.parse("[{"sample1": "...) Commented Oct 26, 2022 at 11:26
  • @ask4you Anytime I use that, it throws this error .. SyntaxError: Unexpected token t in JSON at position 2 Commented Oct 26, 2022 at 11:34
  • @lusc It didn't help. I tried already, I used JSON.parse, it throws this error ... SyntaxError: Unexpected token t in JSON at position 2 Commented Oct 26, 2022 at 11:36
  • Sounds like you're incorrectly stringifying it then. You'll need to debug how it's being sent. The string you've posted is indeed invalid due to missing quotes around the object values eat and eatFruits, but that could easily be a typo on your part Commented Oct 26, 2022 at 11:36

1 Answer 1

0

"[{"sample1": "this", "apple2" : eat},{"sample2": "thisIs2", "apple3" : eatFruits}]"
Your object is the "stringified" JSON. Means whole JSON object represented as string

e.g.

const jsonObj = [{"id": 1, "name": "John"}, {"id": 2, name: "Jane"}];
const strigified = JSON.stringify(jsonObj);
console.log(strigified);

output

'[{"id":1,"name":"John"},{"id":2,"name":"Jane"}]'

This can be reversed by parsing this string as JSON

const original = JSON.parse(strigified);
console.log(original);

output

[{"id": 1, "name": "John"}, {"id": 2, name: "Jane"}]

JSON.strigify() & JSON.parse() are exactly reciprocal methods...

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

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.