0

I am trying to parse a JSON which I will get from Java session variable. I am using code like this:

var foo1 = <%= session.getAttribute("json").toString() %>
var foo = JSON.parse(foo1.toString());
alert(foo.toString());

(Yes, I know scriptlets is Bad, but this is just for temporary). The value which I get with foo1 is a valid JSON (I verified with online validators). But when I try to alert the foo1 I get it as [object,Object] but if I try to parse, I get JSON.parse:Unexcpected character error.

I have uploaded JSON here, in-case if required. Since it is a bit big json string, I cannot post here.

Can someone please help me to know what wrong I am doing in this? To summary I am trying to get JSON String from Java session variable and trying to parse it in Javascript. Any tips on how to do this is appreciated.

0

2 Answers 2

1

try something like this

var foo = <%= session.getAttribute("json").toString() %>
alert(foo.toString());

Reason : your are already getting json object so no need to parse.

var obj = {id:1};    // No need to parse
var obj = "{id:1}"; // Need to parse
Sign up to request clarification or add additional context in comments.

4 Comments

So then I can be able to access elements just like it has been parsed? right?
it's again printing me as "[object,Object]"
ok I will do my bit research again and comeback and reply to you, thanks :)
according to me foo is array so try alert(foo[0].toString())
0

In your case, foo1 is not a string but already a JSON object! That's because you're not assigning a string literal to it, but a javascript-object-structure.

Let's assume the string value of the "json" attribute is { name: "Jack", age: 25 }. Now after JSP processing has been done, the client receives the following:

var foo1 = { name: "Jack", age: 25 }

What you are maybe expecting is:

var foo1 = "{ name: \"Jack\", age: 25 }"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.