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!

3 Answers 3

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;
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().

2
  • IDs should not start with a #, and this won't work in older browsers...this was posted 8 minutes ago as well :) Dec 7, 2010 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 7, 2010 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.

1
  • @Dutchie432 - woops, misread the json tag, the approach is almost identical though, updated. Dec 7, 2010 at 12:52

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.