How do I stringify an array of objects?

前端 未结 3 1002
逝去的感伤
逝去的感伤 2021-01-13 04:48

I have created an array of objects that needs to be stored and kept for another page.

The array of objects is similar to this:

var cheese_array = [
          


        
相关标签:
3条回答
  • 2021-01-13 05:33

    You're missing a , in your 3rd object, after age:

    var cheese_array = [
      {
        name: "Chedder",
        age: "34",
        smelly: true
      },
      {
        name: "Brie",
        age: "4",
        smelly: false
      },
      {
        name: "Blue Stilton",
        age: "13",
        smelly: true
      }
     ];
    
    var jsonObj = JSON.stringify(cheese_array);
    

    This will now work and display correctly.

    0 讨论(0)
  • 2021-01-13 05:38

    Your object misses a comma as shown below:

    name: "Blue Stilton",
        age: "13"//comma is missing here
        smelly: true
    

    JSON.stringify works fine as shown below.

    var cheese_array = [
      {
        name: "Chedder",
        age: "34",
        smelly: true
      },
      {
        name: "Brie",
        age: "4",
        smelly: false
      },
      {
        name: "Blue Stilton",
        age: "13",
        smelly: true
      }
     ];
    console.log(JSON.stringify(cheese_array))

    However I am not sure how you get a log [object Object], [object Object], [object Object] I am presuming you are console logging something else please check that in your code.

    0 讨论(0)
  • 2021-01-13 05:40

    Update JSON with ,(Comma) in

     name: "Blue Stilton",
        age: "13",
        smelly: true
    

    var cheese_array = [
      {
        name: "Chedder",
        age: "34",
        smelly: true
      },
      {
        name: "Brie",
        age: "4",
        smelly: false
      },
      {
        name: "Blue Stilton",
        age: "13",
        smelly: true
      }
     ];
    
    var details = JSON.stringify(cheese_array);
    alert(details);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
提交回复
热议问题