Store JSON Data in local Storage (Java Script)

1 replies
I am trying to store data in the local Storage from my JSON file. But I am getting an empty array in the local Storage. File name is 'data' in the project.
[
"friends": [
{
"id": 0,
"name": "Daugherty Gould"
},
{
"id": 1,
"name": "Foley Carpenter"
},
{
"id": 2,
"name": "Brewer Vinson"
}
]

localStorage.setItem('firstName',data.friends.name );

I am not getting the right output with above code. How can I get all the names in localstorage.

Thank you in advance!
#data #java #json #local #script #storage #store
Avatar of Unregistered
  • Profile picture of the author ltrain_riders
    Originally Posted by manpreetWeb View Post

    I am trying to store data in the local Storage from my JSON file. But I am getting an empty array in the local Storage. File name is 'data' in the project.
    [
    "friends": [
    {
    "id": 0,
    "name": "Daugherty Gould"
    },
    {
    "id": 1,
    "name": "Foley Carpenter"
    },
    {
    "id": 2,
    "name": "Brewer Vinson"
    }
    ]

    localStorage.setItem('firstName',data.friends.name );

    I am not getting the right output with above code. How can I get all the names in localstorage.

    Thank you in advance!
    For starters, data should be valid JSON:

    Code:
    data = [{
      "friends": [{
          "id": 0,
          "name": "Daugherty Gould"
        },
        {
          "id": 1,
          "name": "Foley Carpenter"
        },
        {
          "id": 2,
          "name": "Brewer Vinson"
        }
      ]
    }]
    or

    Code:
    data = {
      "friends": [{
          "id": 0,
          "name": "Daugherty Gould"
        },
        {
          "id": 1,
          "name": "Foley Carpenter"
        },
        {
          "id": 2,
          "name": "Brewer Vinson"
        }
      ]
    }
    Next, you can store all of the 'data' in localStorage as

    Code:
    localStorage.setItem('friends', JSON.stringify(data));
    {{ DiscussionBoard.errors[11621098].message }}
  • Profile picture of the author Rita456
    Banned
    Hello everyone, while studying at the university, I very often faced the difficulties of learning the Java language. Therefore, I asked for help with coding homework for which I am very grateful to them
    {{ DiscussionBoard.errors[11657504].message }}

Trending Topics