0

I am saving from PHP some data in assoc array. There are some Id's putted in an array and then json_encoded:

$ids = array(id => id, id2 => id2);
json_encode($ids);
store in the cookie ...

I am using this plugin for jQuery: http://plugins.jquery.com/cookie/

This is the string, what is stored in the cookie with value: "xxx"

%7B%2222504454%22%3A22504454%7D

path: "/"

domain: ".domain.com"

When I use this one:

var test = $.cookie( 'xxx');

I am receiving only Object as return.

How to read this array?

2
  • Since you encoded the value with json, you are going to need to decode it/address it differently from a simple value. You must be trying to access it as a string and it tells you 'I am an object'. Commented Aug 19, 2013 at 16:30
  • JSON.parse() or $.parseJSON() Commented Aug 19, 2013 at 16:31

1 Answer 1

3

JSON and JavaScript don't support "associative" Arrays1. Their equivalent is an Object.

<?php echo json_encode(array(id => 'foo', id2 => 'bar')); ?>
{ "id": "foo", "id2": "bar" }

Their Arrays are sorted collections with indexes from 0 to length - 1 and can be generated from a non-associative array.

<?php echo json_encode(array('foo', 'bar')); ?>
[ "foo", "bar" ]

Note:

  1. JavaScript Arrays can be given non-numeric keys after they've been instantiated, though such keys will not be counted in the length.

Beyond that distinction: to treat the cookie as either an Object or Array, you'll need to parse it with either JSON.parse() or $.parseJSON().

var test = JSON.parse($.cookie('xxx'));

console.log(test.id);
console.log(test.id2);
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.