3

I've looked around for a Javascript/jQuery function which emulates PHP's json_encode, but all the ones I find (listed bellow) don't work.

  1. http://code.google.com/p/jquery-json/
  2. http://phpjs.org/functions/json_encode:457

To check if it wasn't my array wasn't faulty I used phpjs var_dump with expected results.

Can anyone point me in the right direction?

12
  • What do you mean by doesn't work? Commented Jul 1, 2011 at 16:10
  • Returns an empty result, i.e. [[]]. Commented Jul 1, 2011 at 16:12
  • Well the jquery-json works. I have used it successfully before! Could you add the array or object you are trying to encode? Commented Jul 1, 2011 at 16:15
  • I added some extra detail. :3 Commented Jul 1, 2011 at 16:29
  • 2
    So... why is json2.js no good for this? Commented Jul 1, 2011 at 16:51

1 Answer 1

3

The problem is that you cannot do this:

ret[$(this).attr("id")] = _recursiveItems(this);

because var ret = [] declares ret as an Array and not an Object and $(this).attr("id") is non-numeric (its value is head_1). It is attempting to create an associative array which is not supported.. JavaScript associative arrays are are meant to be numeric and even considered harmful.

If you change the declaration to var ret = {} then you can use jquery-json to convert the object to JSON. Here is a demo using the code in the question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.