Embed JSON element in HTML element using Knockout.js
knockout.js
Solution
You can use the `$data` contextual binding property which represents the current viewmodel and the `ko.toJSON` helper method to output it as a string:
<textarea data-bind="text: ko.toJSON($data)"/>
See in action in this fiddle.
Problem
I am trying to retrieve the raw JSON used to construct a template and have it populate in a textarea element. The structure of the JSON is an array of JSON objects containing three properties which fills out my template fine. What I can't figure out is how to take that raw JSON element on each iteration and display it within a textarea. My description of the issue may be a bit obtuse so hopefully the JSFiddle example describes this better. Javascript ``` function MyViewModel() { this.model = [{ "Key": "c1243328-4796-46c0-bb32-017d5a1ebdd4", "UserId": "02ad61b1-d416-46d4-98ac-d5f6c2b7d104", "Name": "\"old.txt\""}, { "Key": "265c23ea-2d2a-459e-9f51-32837e058d01", "UserId": "02ad61b1-d416-46d4-98ac-d5f6c2b7d104", "Name": "\"sample.dwg\""}]; }; ko.applyBindings(new MyViewModel()); ``` HTML Template ``` <div data-bind="template: { name: 'template', foreach: model}"></div> <script type="text/html" id="template"> <p> <span data-bind="text: Key"></span> <span data-bind="text: UserId"></span> <span data-bind="text: Name"></span> </p> <p><textarea data-bind="text: ???"/></p> </script> ``` I would like to see the actual JSON element in the textarea and I am not sure what is required to accomplish this. The above running in jsFiddle