0

This is what I'm getting from server

['model':{"category":[{"id":1}],"food":[{"id":1}].... // long json here

How can I use jquery/javascript to parse to get category id and food id? I tried to use

JSON.parse(data)

or

JSON.stringify(data)

And after that, doing

$.each(data, function (i, x) {

it will give me each letter of all array. How can I parse it correctly, getting the ids that I want?

fsi
  • 1,319
  • 1
  • 23
  • 51
  • How are you getting it from the server? – LcSalazar Dec 12 '14 at 20:26
  • What you need to iterate over ? Do you need to iterate over category ? – Sariq Shaikh Dec 12 '14 at 20:28
  • The single-quotes around "model" are invalid JSON syntax. If your server is really sending that, you'll get errors when you try to parse it. – Pointy Dec 12 '14 at 20:31
  • did you try accessing data directly? you are probably using a method like $.getJSON that parses the response for you. Also [model:{}] is wrong it should be [{"model": {..}}] instead – Furqan Zafar Dec 12 '14 at 20:32
  • @Pointy YES! It's invalid, you are right, I saw it on console. Thanks for pointing that! – fsi Dec 12 '14 at 20:34

2 Answers2

0

JSON.parse(data) will turn the data you showing into a JavaScript object, and there are a TON of ways to use the data from there. Example:

var parsedData = JSON.parse(data),
    obj = {};

for(var key in parsedData['model']){
    obj[key] = parsedData['model'][key]['id'];
}

Which would give you a resulting object of this:

{category:1, food:1}

This is based on the limited example of JSON you provided, the way you access it is entirely dependent on its structure. Hopefully this helps get you started, though.

PlantTheIdea
  • 16,061
  • 5
  • 35
  • 40
-1

You want to use JSON.parse(), but it returns the parsed object, so use it thusly:

var parsed = JSON.parse(data);

then work with parsed.

Cameron Roberts
  • 7,127
  • 1
  • 20
  • 32