1

i am working on parsing a JSONobject. so the thing which i am trying to do is to parse the object using javascript from json and to assign it to an array. any help or suggestions. Thank in advance. here is my code.

my javascript code to parse.

  name = JSON.parse(cooldrinkname);

and one of my json object code is.

       {
            "shopID" : "erer2123",
            "shoname" : "saravana store",
            "cooldrinkname" : "pepsi",
            "cost" : "10"
        },

so from the above code. i am trying to extract the cooldrink name and trying to assing in a array variable name. Thanks in advance.

xdazz
  • 158,678
  • 38
  • 247
  • 274
Hk M
  • 73
  • 2
  • 10

2 Answers2

1

Your JSON is not an array, so you cannot assign it to an array. You should first parse the JSON to an object, then you can add the cooldrinkname to an array:

var myjson = '{ "shopID" : "erer2123", "shoname" : "saravana store", "cooldrinkname" : "pepsi", "cost" : "10" }';
var obj = JSON.parse(myjson);
var cooldrinknames = [];
cooldrinknames.push(obj.cooldrinkname);
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • Yes this is right Kenneth. but i am using a external .json file for my project. so . is this the same way which i can implement for external .json file? – Hk M May 29 '13 at 07:30
  • Sure, you just need a way to pull in the json. – Kenneth May 29 '13 at 07:34
0

try this and hope it helps

var myjson = '{ "shopID" : "erer2123", "shoname" : "saravana store", "cooldrinkname" : "pepsi", "cost" : "10" }';
var cooldrinknames = [JSON.parse(myjson)];
console.log(cooldrinknames); // to view object array in dev. console. 
Lewis E
  • 327
  • 1
  • 7
  • i am using a external .json file. so is there any way to parse an external .json file and store it in an array. – Hk M May 29 '13 at 08:01
  • well theres a couple of ways to get this you could ajax it in Ex. $.get $.post $.ajax or you could use the .load function to bring in your data. if you choose ajax you could have it parse for you and return the array if you use the .load you will have to parse in code like above. – Lewis E May 29 '13 at 08:12