Best way to store a JSON

Asked

Viewed 499 times

2

Hello, I get a json on this request template

{  
   "alunos":[  
      {  
         "ID":"1",
         "Nome":"Pedro",
      },
      {  
         "ID":"2",
         "Nome":"Lucas",
      },
      {  
         "ID":"3",
         "Nome":"Joana",
      }
   ]
}

I would like a good example of how to store it in a local variable, for later use, array would be a good choice ?

  • 2

    Look, I don’t know if I understood your question correctly, but it wouldn’t be good to use for example: var obj = JSON.parse(jsonString); ???

  • It’s a good way?

  • 2

    Actually, I don’t see another one! This way, you already turn the string into an object and do what you want with it. Do you understand? Only make this change: var obj = JSON.parse(jsonString) || {}; Because if it cannot convert, it returns an empty obj...

  • 1

    What is the concrete doubt you have ? Or what are you unable to do with this information ? What @Diegosantos said already solves the problem and stores the information in an object that is ideal in almost all cases.

  • to save in obj I always have to write obj, or I can put something else ?

  • 1

    That’s just the variable name. You can have any name you want.

  • Okay thanks, doubt settled

Show 2 more comments

1 answer

1


The best way would be to convert to a javascript object.

Most browsers support JSON.parse(), which is defined in ECMA-262 5th edition (the specification on which Javascript is based):

var json = '{"teste":1,"teste2":true}',
var obj = JSON.parse(json);

Here are some references worth checking to better understand how the json parse works in javascript:

https://msdn.microsoft.com/pt-br/library/cc836458(v=vs.94). aspx

https://msdn.microsoft.com/pt-br/library/cc836466(v=vs.94). aspx

https://msdn.microsoft.com/pt-br/library/cc836459(v=vs.94). aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.