0

I saw this answer dealing with getting data from JSON. I'm trying to do almost the same, but my JSON is structured differently as far as arrays/objects and I'm not sure how to parse it the same way.

My JSON is in this format and I'm trying to write a function to find certain elements based on the linked question, but without keys for the elements in the json, not sure how to target things. Or do I need to try and rework the out put of my json? (which is being created by json_encode from a modified codeigniter db query.

$(function() {
var json = [
  {

    "answer": [

      "4555"

    ],
    "answer_string": "4555|",
    "qid": "70",
    "aid": "742"
  }, 
 {

    "answer": [

      "monkeys",
      "badgers",
      "monkeybadgers"

    ],
    "answer_string": "monkeys|badgers|monkeybadgers|",
    "qid": "71",
    "aid": "742"
  }
];
    $.each(json[], function(i, v) {
        if (v.qid= "70") {
            alert(v.answer[0]);
            return;
        }
    });
});​

jsfiddle

I need to find answer[0] where qid matches a certain number.

Community
  • 1
  • 1
Damon
  • 10,493
  • 16
  • 86
  • 144

2 Answers2

1

Your javascript is messed up. See updated fiddle:

http://jsfiddle.net/jQmyf/2/

Specifically: if (v.qid= "70") { that should be v.qid==

and $.each(json[] should just be $.each(json

aquinas
  • 23,318
  • 5
  • 58
  • 81
  • thanks! actually did have == in the code. The reason it wasn't working in my code turns out it was because of a different problem :p – Damon Apr 26 '12 at 14:32
0

You should give each only the name of the array:

$.each(ja, function(i, v) {

Use comparison instead of assignment inside if:

if (v.qid== "70") {

$(function() {
    var ja= [
      {
        "answer": [

          "4555"
        ],
        "answer_string": "4555|",
        "qid": "70",
        "aid": "742"
      }
    ];
    $.each(ja, function(i, v) {
        if (v.qid== "70") {
            alert(v.answer[0]);
            return;
        }
    });
});​

Updated Fiddle:

SadullahCeran
  • 2,425
  • 4
  • 20
  • 34