4

I have a JSON Array that is defined as follows:

var myItems = {
  "data": [
    { "id":1, "firstName":"bill", "lastName":"smith" },
    { "id":2, "firstName":"john", "lastName":"apple" },
    { "id":3, "firstName":"will", "lastName":"long"}
  ]
};

I need to store this array in a hidden HTML element so that I can pass it to my server-side code in string format. My problem, I'm not sure how to do this. Can someone tell me how to do this?

Thank you!

Villager
  • 6,569
  • 22
  • 65
  • 87

3 Answers3

6

Essentially, you want to serialize your array into json, and then specify where you want to store the resulting string value..

document.getElementById('yourHiddenField').value = jsonString;
Community
  • 1
  • 1
Dutchie432
  • 28,798
  • 20
  • 92
  • 109
2

Use this code:

document.getElementById('input').value = JSON.stringify(myItems);

See here for the JSON documentation:

NOTE: All moderns browsers provide at least partial support for native JSON parsing (JSON.parse() and JSON.stringify(). Older browsers don't. As suggested by Nick Craver, you can use json2.js for this, and most JavaScript frameworks provide support as well (and most will try to detect the native functions or use their own versions). For instance Dojo's Dojo.toJson() and Dojo.toJson().

Community
  • 1
  • 1
haylem
  • 22,460
  • 3
  • 67
  • 96
  • IDs should not start with a `#`, and this won't work in older browsers...this was posted 8 minutes ago as well :) – Nick Craver Dec 07 '10 at 12:57
  • @Nick: yes and I was saying it wouldn't (or I was typing it at the time). I even later updated it to give you credit for the json2.js solution. – haylem Dec 07 '10 at 13:10
1

What you have is an object literal, not JSON yet...however we can easily convert it to JSON using JSON.stringify(), like this:

document.getElementById("myHiddenInput").value = JSON.stringify(myItems);

To support older browsers without native JSON support (IE <8), include json2.js and the code above will still work.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155