0

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 } }

user2955610
  • 815
  • 2
  • 9
  • 15
  • 1
    please replace JSON object with object. [JSON](http://json.org/) is always a string. – Nina Scholz May 25 '16 at 14:03
  • 1
    What is in `mazeFromServer` and why do you `stringify` it? – MysterX May 25 '16 at 14:05
  • What you mean by JSON string?? – brk May 25 '16 at 14:06
  • @MysterX mazeFromServer is the JSON that I I received by using the $.getJSON call. – user2955610 May 25 '16 at 14:07
  • JSON is a serialized object (after serialization it's a string) with special notation. an object is just an object. – Nina Scholz May 25 '16 at 14:09
  • 1
    You're stringifying something which is already a string, then unstringifying the results. Skip the first step. – Daniel Beck May 25 '16 at 14:10
  • 2
    Yeah, get rid of `var jsonStringer = JSON.stringify(mazeFromServer);` and change the obj line to `var obj = JSON.parse(mazeFromServer);` – Anialation May 25 '16 at 14:11
  • Have you tried: alert(typeof obj); – SPlatten May 25 '16 at 14:12
  • 1
    This question is tagged as jQuery (though no jQuery code is shown). That library will normally convert from/to JSON automatically in many circumstances so you'll probably get better answers if you provide some context. – Álvaro González May 25 '16 at 14:12
  • If I don't use stringify it throws me an exception "Unexpected Token" – user2955610 May 25 '16 at 14:12
  • @SPlatten yes, it tells me that it is a String – user2955610 May 25 '16 at 14:14
  • In that case you can't get .Name from it as it isn't an object. – SPlatten May 25 '16 at 14:14
  • Using the browsers console window is extremely helpful. Adding a line `console.log(mazeFromServer);` to see what mazeFromServer actually looks like would be really helpful to see if it's already an object or not. That will tell you way more, way faster, about the variable. – Anialation May 25 '16 at 14:15
  • And what if you just use `var stringName = mazeFromServer.Name`??? – A. Wolff May 25 '16 at 14:17
  • @Anialation the Console.log shows me what the Object looks like in the correct form – user2955610 May 25 '16 at 14:18
  • Wait. If you're using `$.getJSON` to get `mazeFromServer`, jQuery should be doing the parsing for you -- you should neither need to `.stringify` nor `.parse` the results -- just use `mazeFromServer` as is. Have you tried `mazeFromServer.Name`? – Daniel Beck May 25 '16 at 14:18
  • Yes i tried writing var name = mazeFromServer.Name; and still does not draw the Name – user2955610 May 25 '16 at 14:21
  • And what happened? – Daniel Beck May 25 '16 at 14:22
  • Nothing. var name = mazeFromServer.Name; $('.nameLabel').text(name); Nothing in the label changes – user2955610 May 25 '16 at 14:25
  • @user2955610 if the console log specifically said the item was an object, then you should be good to go. Try `console.log(mazeFromServer.Name);`. If that works, then your problem is somewhere else in your code. If not, you may still need the `JSON.parse(mazeFromServer);`. – Anialation May 25 '16 at 14:26
  • @user2955610 The console shows me: Uncaught ReferenceError: Name is not defined – user2955610 May 25 '16 at 14:27
  • @user2955610 Then try: `var obj = JSON.parse(mazeFromServer); console.log(obj.Name);` – Anialation May 25 '16 at 14:28
  • Console Output: SyntaxError: Unexpected token – user2955610 May 25 '16 at 14:30
  • That error message indicates that what you're trying to parse isn't in fact JSON. What does `console.log(typeof(mazeFromServer))` result in? And what are the *exact* contents of `mazeFromServer`? Is there any chance it includes a header, or some other value, along with the JSON (as in [this question](http://stackoverflow.com/questions/18561556/syntax-error-unexpected-token)?) – Daniel Beck May 25 '16 at 14:38
  • 1
    @user2955610 It looks like your JSON data has a `;` at the end. I thought I tested for that when checking it out but I guess my IDE filtered it out. That can't be there. – Anialation May 25 '16 at 14:38
  • @Anialation it doesnt, where did you see that? – user2955610 May 25 '16 at 14:55
  • @Anialation Even if i try after that call eg: $.getJSON("ProgressServlet", function(data){ if (data.progress != current) mazeFromServer = data.progress; $('.mazeLabel').text(mazeFromServer.Name); This doesnt change the label – user2955610 May 25 '16 at 15:02
  • @user2955610 So right before `$('.mazeLabel').text(mazeFromServer.Name);` add a console log for `mazeFromServer` and `mazeFromServer.Name` and see what happens. If those fail, try `mazeFromServer = JSON.parse(data.progress);` and see what the console logs give you. – Anialation May 25 '16 at 15:05
  • console.log(mazeFromServer) Shows we all the contents of the object in its correct form console.log(mazeFromServer.Name) shows "underfined" – user2955610 May 25 '16 at 15:08
  • What exactly does `console.log(mazeFromServer)` say though? If it's a proper object, it should look like this (depending on browser): `Object {Name: "Game1", Level: "Two"}`. It needs to say `Object` at the begining. [Example](https://jsfiddle.net/qvne2c7w/) – Anialation May 25 '16 at 15:13
  • It doesnt say object next to it – user2955610 May 25 '16 at 15:19
  • { "Name": "Game1", "Maze": "111111110010010101000000000", "Start": { "Row": 3, "Col": 3 }, "End": { "Row": 1, "Col": 3 } } – user2955610 May 25 '16 at 15:19
  • @user2955610 So it's not an object yet and you'll need the like `mazeFromServer = JSON.parse(data.progress);` – Anialation May 25 '16 at 15:30
  • Can't do that, it wont accept the type – user2955610 May 25 '16 at 15:37
  • Then I'm not sure, we're missing something but I'm not sure what. Also, are you sure `if (data.progress != current)` is triggering correctly? You could do a `console.log(data.progress != current);` to check – Anialation May 25 '16 at 16:41

1 Answers1

1

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);
    }
SPlatten
  • 5,334
  • 11
  • 57
  • 128