1

I have a empty json array.

shoppingCart: []

I have a json object.

let product = {"name": "name", "price": "price", "quantity": "quantity", "logoPath": "logoPath"};

I am trying to add json object to json array.

let obj = JSON.parse(state.shoppingCart);
obj.push(product);
state.shoppingCart = JSON.stringify(obj);

I got this error:

"SyntaxError: Unexpected end of JSON input"

I wanna add many object to empy array like that:

shoppingCart: [{id: 1, name: name1}, {id: 2, name: name2}, {id: 3, name: name3}]

Where is my mistake?

3
  • What does the literal state of shoppingCart and product look like at the time of .push()? Commented Apr 8, 2020 at 15:16
  • @symlink Both of them same as above. Commented Apr 8, 2020 at 15:22
  • 1
    for your information, first code is not a json array, this is an empty javascript object litteral. JSON is a data format, "coded" as a string ; same thing with the second code Commented Apr 8, 2020 at 15:23

2 Answers 2

4

Skip the line where you try to JSON.parse() shoppingCart

let shoppingCart = []

let product = {
  "name": "name", 
  "price": "price", 
  "quantity": "quantity", 
  "logoPath": "logoPath"
}

//let obj = JSON.parse(shoppingCart)
shoppingCart.push(product)
shoppingCart = JSON.stringify(shoppingCart)

console.log(shoppingCart)

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

Comments

1

I'm not sure I understood the question clearly...but if you want arr of json is go something like this:

let arr = []
let myObj1 = {"name": "name1", "price": 1, "quantity": 1, "logoPath": "logoPath1"};
let myObj2 = {"name": "name"2, "price": 2, "quantity": 2, "logoPath": "logoPath2"};
arr.push(myObj1)
arr.push(myObj2)
console.log(arr)

hope that is helpful

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.