How to create a JSON using jquery?

Asked

Viewed 2,591 times

3

How do I create a JSON with several different names?

Equal: [{name: "john"}, {name: "peter"}]

Could someone give me an example?


I tried to do so, but why does he always return the last item twice? Like John in the first and then Peter twice?

  $(".item-tbody .nome").each(function ()
   {
       obj.nome = $(this).parent().find('.nome').text();

        arrayObj.push(obj);

         nomeArray = JSON.stringify(arrayObj);
          alert(nomeArray);

   });
  • Will be JSON.stringify('[{nome: "joão"}, {nome: "pedro"}]'); ? https://jsfiddle.net/rwctqhu9/ . I don’t think there’s a better way to use jquery, simply use the native javascript function

  • Yes. It comes from a single variable. Type the two comes from the name variable. How do I break the two that look the same in the above model?

  • Isn’t that like the link I put on top? You want two jsons, one for each obj inside the array, that’s it?

  • Yes, like this one. Only John and Peter come from a single variable. How do I break it so it looks like the one you said above?

  • I have the variable name, which comes: John and Peter.

  • Want each name in a different variable? eg: var name1 = 'joão'; var name2 = 'pedro';

  • I have the variable name, which comes: John and Peter right? It comes with these two names, but I want it to be broken and put like this: [{name: "john"}, {name: "peter"}]

  • So https://jsfiddle.net/7vr9Lq3h/1/?

  • Dude I did so: obj.name = $(this). Parent(). find('. name'). text(); arrayObj.push(obj); nameArray = JSON.stringify(arrayObj); Alert(nameArray);

  • He appears: [{"name":"john paul"}]. As I break them?

  • Yes. It even worked, but he still cuts out the names: John, he puts: {"name":"J"},{"name":"the"} understand? var people = $(this). Parent(). find('. name'). text(); var Names = []; for(var i = 0; i < people.length; i++) { Names.push({name: people[i]}); } Alert(JSON.stringify(Names));

  • Thank you. I will try looking in another forum.

Show 7 more comments

1 answer

2

Your JSON is not valid! Paste it on that website and validate it, your JSON returns:

Expecting string or }, not [.

I created a valid JSON of names for you. Remembering that { } = objeto and [ ] = Array. Read more about JSON here.

[{ "nome":"João"},{"nome":"Pedro"}]

obj =
[
   {
      "nome":"João"
   },
   {
      "nome":"Pedro"
   }
]

console.log(obj[0].nome)
console.log(obj[1].nome)

Browser other questions tagged

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