Reputation: 835
I am trying to create a JSON object from a string in the correct JSON format I received from my .jsp file. I get the string and convert it as follows:
try{
var jsonStringer = JSON.stringify(mazeFromServer);
var obj = JSON.parse(jsonStringer);
}catch (e){
window.alert(e);
}
This works without errors. When I try to manipulate or get information from that object, for instance:
var stringName = obj.Name;
Although i have a Name field in my JSON, nothing happens. I checked my JSON on the JSON validation website and everything was fine. What is wrong?
JSON looks like this:
{
"Name": "Game1",
"Level":"Two"};
When I declare JSON by myself, it works fine. But when I receive it in a String format from an outside source it doesn't work.
Any Ideas?
EDIT:
mazeFromServer is a string received from an external server. In my servlet i am adding it as follows:
JSONObject obj = new JSONObject();
obj.put("progress", fromServer);
And then running this Query in my jsp file:
function getMaze(){
$.getJSON("ProgressServlet", function(data){
if (data.progress != current)
mazeFromServer = data.progress;
$('.mazeLabel').text(mazeFromServer);
stopJSONCheck();
})
}
The mazeFromServer Looks as follows:
{
"Name": "Game1", "Maze": "111111111110000000", "Start": { "Row": 3, "Col": 3 }, "End": { "Row": 1, "Col": 3 } }
Upvotes: 0
Views: 3034
Reputation: 5758
You should modify your code as follows:
try{
var obj;
if ( typeof mazeFromServer != "string" ) {
obj = jsonStringer;
} else {
var jsonStringer = JSON.stringify(mazeFromServer);
if ( typeof jsonStringer != "string" ) {
throw("mazeFromServer cannot be converted to JSON string");
}
obj = JSON.parse(jsonStringer);
}
if ( typeof obj != "object" ) {
throw("'obj' is not an object, it is: " + typeof obj);
}
} catch (e) {
window.alert(e);
}
Upvotes: 1