0

I am trying to work with the bootstrap typeahead plugin but I need to get my JSON to output correctly.

Per the last example on this page it appears you can use more than just a key->value in the JSON response: http://twitter.github.io/typeahead.js/examples/

Here is what my PHP code looks like:

$objDB = new DB;
    $xml = $objDB->setStoredProc('shadowGetEmp')
                -> setParam("ntid", $query)
                -> execStoredProc()
                -> parseXML();


        foreach($xml->emp as $emp){

            $name = $emp->FirstName .' '. $emp->LastName;
            $qid = $emp->QID;
            $empID = $emp->EmpID;

            $users[] = array('name'=> $name, 'qid'=> $qid, 'empID'=> $empID);
        }

     header('Content-Type: application/json');
     echo json_encode($users);

The JSON response looks like this:

[{
    "name": "John Doe",
    "qid": {
        "0": "Q1234"
    },
    "empID": {
        "0": "123"
    }
}, {
    "name": "Bob Jones",
    "qid": {
        "0": "Q5678"
    },
    "empID": {
        "0": "456"
    }
}, {
    "name": "Mike James",
    "qid": {
        "0": "Q2233"
    },
    "empID": {
        "0": "789"
    }
}, {
    "name": "Harry Potter",
    "qid": {
        "0": "Q2212"
    },
    "empID": {
        "0": "223"
    }
}]

How can I format the response to a correct JSON output?

I think its because of the associative array but not sure how to include more than just a key/value and format the JSON.

5
  • What's wrong with that JSON? Looks fine to me...
    – elclanrs
    Dec 6, 2013 at 2:40
  • why are there 0 values in qid and empid but not name?
    – SBB
    Dec 6, 2013 at 2:42
  • I see, so it should be an array instead?
    – elclanrs
    Dec 6, 2013 at 2:43
  • just trying to make it like twitter.github.io/typeahead.js/data/films/queries/l.json but instead of tokens just another value.
    – SBB
    Dec 6, 2013 at 2:49
  • so name, qid and empid are technically the keys and the values need to be in their respective place
    – SBB
    Dec 6, 2013 at 2:50

1 Answer 1

0

It looks like $emp->QID and $emp->EmpID are returning an array with one element.

Either fix the code that assigns those variables in the $emp instance (better, seems like those should just be number/id values, not an array) or compensate for it here (dirty solution, but will work).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.