9

I have a JSON object that doesn't have a key for the three values given (each is an array) and I want to parse through them. How might I do this in JQuery?

[
    {
        "cid": "3",
        "pid": "0",
        "nid": "12",
        "uid": "4",
        "subject": "test2",
        "hostname": "127.0.0.1",
        "created": "1374084646",
        "changed": "1374084645",
        "status": "1",
        "thread": "02/",
        "name": "chrisr",
        "mail": "",
        "homepage": "",
        "language": "en",
        "uuid": "e4729a69-7f6f-4091-98a0-0a040fe683f1",
    },
    {
        "cid": "2",
        "pid": "0",
        "nid": "13",
        "uid": "4",
        "subject": "TEST comment 2",
        "hostname": "127.0.0.1",
        "created": "1374072245",
        "changed": "1374072244",
        "status": "1",
        "thread": "01/",
        "name": "chrisr",
        "mail": "",
        "homepage": "",
        "language": "en",
        "uuid": "b4d5a084-8aa3-4828-b6e4-17396cbaf2f6",
    },
    {
        "cid": "1",
        "pid": "0",
        "nid": "12",
        "uid": "4",
        "subject": "test comment",
        "hostname": "127.0.0.1",
        "created": "1374072176",
        "changed": "1374072175",
        "status": "1",
        "thread": "01/",
        "name": "chrisr",
        "mail": "",
        "homepage": "",
        "language": "en",
        "uuid": "7ade4906-7d6e-4cad-9f97-7f43eadea731",
    }
]
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
CR47
  • 843
  • 4
  • 12
  • 33
  • This can be done without jQuery. – turnt Jul 17 '13 at 18:46
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) or alternatively [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Bergi Jul 17 '13 at 18:47
  • 1
    Just fix the formatting (so it's valid) then use `jQuery.parseJSON()`. I include a working fiddle in my answer below... – jahroy Jul 17 '13 at 18:59

2 Answers2

6

Your JSON is not valid.

Once you create a valid JSON string, parsing it is very simple.

Use the following steps:

  1. remove the commas after the last property of each object
  2. remove the newlines
  3. wrap the JSON text in single quotes
  4. call jQuery.parseJSON() on the text

Here's a working fiddle.

It does something like this:

var jsonText = '[ { "cid": "3", "pid": "0", "nid"...} ]';
var jo = $.parseJSON(jsonText);
jahroy
  • 22,322
  • 9
  • 59
  • 108
3

If you have the JSON in string form, you can use JSON.parse[MDN] to get it in object form, and then do with it what you need to.

Modern browsers have this function natively - no jQuery necessary - but you can also include it yourself from one of these locations:

For a more complete list, see JSON.org.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91