# Cookie has key/value pairs and lost order after JSON decode

**URL:** <https://www.ruby-forum.com/t/cookie-has-key-value-pairs-and-lost-order-after-json-decode/189297>\
**Category:** Rails\
**Created:** [May 28, 2010, 9:07am UTC](https://www.ruby-forum.com/t/cookie-has-key-value-pairs-and-lost-order-after-json-decode/189297 "2010-05-28T09:07:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![winterheat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7993a0/32.png) [@winterheat](https://www.ruby-forum.com/u/winterheat)\
**Post date:** [May 28, 2010, 9:07am UTC](https://www.ruby-forum.com/t/cookie-has-key-value-pairs-and-lost-order-after-json-decode/189297/1 "2010-05-28T09:07:44Z")

</div>

If a cookie has several items, and is encoded as JSON text as the value  
of the cookie, the order is actually apparent in the cookie’s text

But if JSON.decode is used:

ActiveSupport::JSON.decode(cookies[‘item\_list’])

and the result is actually in a hash, then the ordering is lost…

Is it true that if the original JSON object has an array of hashes (1  
key and 1 value), then the order can be preserved?

But what if the original JSON object was a hash of key / value pairs,  
and is already in many users’ cookies, then is there a way to somehow  
keep the order?

---

<div class="post-metadata">

**Author:** ![winterheat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7993a0/32.png) [@winterheat](https://www.ruby-forum.com/u/winterheat)\
**Post date:** [May 28, 2010, 10:09am UTC](https://www.ruby-forum.com/t/cookie-has-key-value-pairs-and-lost-order-after-json-decode/189297/2 "2010-05-28T10:09:41Z")

</div>

> ActiveSupport::JSON.decode(cookies[‘item\_list’])
> 
> and the result is actually in a hash, then the ordering is lost…
> 
> Is it true that if the original JSON object has an array of hashes (1  
> key and 1 value), then the order can be preserved?
> 
> But what if the original JSON object was a hash of key / value pairs,  
> and is already in many users’ cookies, then is there a way to somehow  
> keep the order?

No, Ruby Hash objects are specifically unordered. You could create an  
ActiveSupport::OrderedHash instead of a Hash and store that in the  
cookie instead if you need to maintain ordering? Or Array support  
ordering so an array would work.

Cheers,

Andy
