2

I would like my webpage to display what resembles JASON Parser does (right panel). I first installed JSONView on my Chrome.

Then I composed a string {"isbn":"asdf","name":"qwer","price":1} which I fed to JSON Parser and made sure it indeed obeyed JSON format.

Eventually, I attempted to display it on my webpage by doing:

out.println("{\"isbn\":\"asdf\",\"name\":\"qwer\",\"price\":1}\");

but it was simply displayed like any other normal String instead of being formatted like this. enter image description here How do I manage to make my webpage automatically display JSON formatted?

Thanks!

Sean
  • 713
  • 1
  • 10
  • 28

1 Answers1

0

Edit: I didn't realise this was JSP. The answer I'm giving relates to using the JavaScript method JSON.stringify() which you'd somehow achieve within client-side JavaScript within your JSP project.


Use JSON.stringify() to 'pretty-print' the original JavaScript object.

For example, to have two spaces of indentation:

var str = JSON.stringify(obj, null, 2);


If this has to be achieved within Java code then you could use the GSON library. Example: Pretty-Print JSON in Java

Community
  • 1
  • 1
Trevor
  • 10,903
  • 5
  • 61
  • 84
  • Thank you to begin with.... I try not to turn this into a step-by-step tutorial for noob like me, but I am writing JSP and my Intellij told me "var" and "JSON" could not be resolved. Am I missing JSON library? – Sean Dec 23 '15 at 14:07
  • 1
    Oh, sorry. `JSON.stringify()` is a JavaScript method available natively on most browsers (I think). I didn't notice the `out.println` and didn't realise this was JSP. I know nothing about JSP I'm afraid (other than that it's based on Java). If this task must be done in Java (or by whatever the end result actually is - I don't know if JSP 'compiles' out to JavaScript or whatever) then try using GSON (see http://stackoverflow.com/questions/4105795/pretty-print-json-in-java). Or alternatively can you embed a snippet of JavaScript to do the `JSON.stringify()`? – Trevor Dec 23 '15 at 14:15