4

This is probably a really easy question, but I can't find anything that works.

I'm trying to take a json result and just write it into the inner html of a div to see what it looks like.

I have something like this:

$.getJSON("someurlthatgivesmejson",
    function(data){         
        $("#jsonmodel").html(data);  // what should this be??
    });
  });

UPDATE

I was able to get it to display some text by using

$("#jsonmodel").html($.param(data));

However, it's not formatted like how the browser displays a json result, like the structure of the javascript object.

Joseph
  • 25,330
  • 8
  • 76
  • 125

5 Answers5

5

You can use jquery-json library

`$('#jsonmodel').html($.toJSON(data));`
Jirapong
  • 24,074
  • 10
  • 54
  • 72
2

depends on what the data is. if you want to write it as a string, then you should use the $.get method to get it, that way its not converted into a js hash for you

mkoryak
  • 57,086
  • 61
  • 201
  • 257
2

You can use JSON.stringify natively within browsers and just pass in spacer arguments like this:

JSON.stringify(data, null, 2)

Demo in jsFiddle & Stack Snippets

// listener
$(":input").on("keyup change", WriteFormDataToDiv);

// call on load
WriteFormDataToDiv()

function WriteFormDataToDiv() {
  var data = $(":input").serializeArray()
  var html = JSON.stringify(data, null, 2)
  $("#formdata").html(html)
}
pre {
  padding: 15px;
  background: lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<input type="text" name="cat"     value="frida" />
<input type="text" name="dog"     value="buddy" /><br/>
<input type="text" name="food"    value="pizza" />
<input type="text" name="dessert" value="ice cream" />

<pre id="formdata"></pre>

Further Reading

KyleMit
  • 30,350
  • 66
  • 462
  • 664
0

data is a JavaScript object, you need a string.

code_burgar
  • 12,025
  • 4
  • 35
  • 53
0

Here is the function I used:

function unjsEncode(string){
            var newstring = string.replace(/\\x/g,'%');
            newstring = newstring.replace(/\\n/g,'');
            newstring = newstring.replace(/\\"/g,'"');
            newstring = decodeURIComponent(newstring);
            return newstring;
    }

thanks to http://bytes.com/topic/javascript/answers/169509-how-decrypt-garbled-javascript And I hope this helps out!

vaene
  • 189
  • 2
  • 12