1

I'm having a problem with getting json data. I created 2 examples. One works, but the other doesn't. And guess which one I need? Yup, the one that doesn't work. Here is the code.

I have a web service that outputs json data but for some reason it add extra brackets [] to the string and it's also missing the single quotes ' '. If you look at the code that doens't work, you'll see that i'm manually removing the brackets and adding the single quotes. I have a div that i write the string to and it's valid Json data. If I take that string and manually declare a new variable with it, the jQuery.parseJSON works fine. But it I parse the newly created object, it doesn't work. Anybody have any ideas?

Works Fine

 $.ajax({
    type: "POST",
    async: false,
    contentType: "application/json; charset=utf-8",
    url: "StudiesWebService.asmx/EventList",
    data: "{}",
    dataType: "json",
    success: function(msg) {
        var obj = jQuery.parseJSON('{ "id": 1, "title": "Jack STuff", "start": "\/Date(1318939200000)\/", "end": "\/Date(1318950000000)\/", "allDay": false }, { "id": 2, "title": "asdfasdfasdf", "start": "\/Date(1319025600000)\/", "end": "\/Date(1319025600000)\/", "allDay": false}');
        var events2 = [];
        events2.push({
            title: obj.title,
            allDay: obj.allDay,
            start: 'Tue, 18 Oct 2011 10:00:00 EST',
            end: 'Tue, 18 Oct 2011 11:00:00 EST'
        });

        callback(events2);

    },
    error: function(e) { $(".external-events").html("An Error Occured" + e); }
});

Doesn't Work:

$.ajax({
    type: "POST",
    async: false,
    contentType: "application/json; charset=utf-8",
    url: "StudiesWebService.asmx/EventList",
    data: "{}",
    dataType: "json",
    success: function(msg) {
        var myObj = new String(msg.d);

        myObj = myObj.replace("[", "");
        myObj = myObj.replace("]", "");
        myObj = "'" + myObj + "'";

        //at this point myObj output to this:
        //'{"id":1,"title":"Mike STuff","start":"\/Date(1318939200000)\/","end":"\/Date(1318950000000)\/","allDay":false},{"id":2,"title":"asdfasdfasdf","start":"\/Date(1319025600000)\/","end":"\/Date(1319025600000)\/","allDay":false}'

        var obj1 = jQuery.parseJSON(myObj);
        alert(obj1.id);  //alert doesn't come up

        var events = [];

        events.push({
            title: obj1.title,
            allDay: obj1.allDay,
            start: 'Tue, 18 Oct 2011 10:00:00 EST',
            end: 'Tue, 18 Oct 2011 11:00:00 EST'
        });

        callback(events);
    },
    error: function(e) { $(".external-events").html("An Error Occured" + e); }
});
3
  • Thank you everyone for your help. You not only fixed this error but a few others that I had in my code. I just started working with javascript and jquery recently and I'm having a tough time. Coming from a vb.net environment and learning c# and jquery is kicking my behind. Commented Oct 20, 2011 at 16:47
  • Do you control the webservice that's spitting out the bad json? If you do, why not fix that rather than trying to compensate here? Commented Oct 20, 2011 at 16:51
  • Yes, this is my web service. Not sure what I'm doing wrong here either: var eventList = from e in _db.events select new { id = e.event_id, title = e.title, start = e.from_date, end = e.to_date, allDay = false }; var rows = eventList.ToArray(); JavaScriptSerializer jss = new JavaScriptSerializer(); string strJSON = jss.Serialize(rows); return strJSON; Commented Oct 20, 2011 at 16:53

5 Answers 5

1

if you remove this line

myObj = "'" + myObj + "'";

it should be fine. In the upper example, the '' enclose the string. they are not actually part of the string itself, so they do not need to be added to myObj

Also, your json has [] around it because it's actually returning a 2-element array ([{obj1},{obj2}]), so you should either iterate that array, or pull out the first element (obj[0])

Sign up to request clarification or add additional context in comments.

6 Comments

It's also the fact he's removing the [ and ], because he's receiving an array of objects.
That did it. Thank you for the help. Both on the line that I had to remove and the replace code.
@Matt yeah, just noticed that. it's fixed
@MikeB55, I updated my answer. don't use the replaces I posted earlier. instead do something like jQuery.parseJSON(myObj)[0];
I tried jQuery.parseJSON(myObj)[0]; but it doens't work. How can I iterate over all of the json objects and output them to a div?
|
1

Adding the single quotes around the whole object would turn it into a single string... so you probably don't mean to do that.

I'm not sure where the brackets are that you're removing, but you probably want to keep those because the objects within them will be treated as an array.

Comments

1
  1. Why are you removing the [ and the ]? Your turning something which is valid JSON into something that's invalid.

    The response you're getting is an array (denoted by the [ and ]) of objects (denoted by { and }).

    You'd get away calling jQuery.parseJSON on the input as you receive it, however because you've set the dataType: "json", jQuery parses it for you, so data should be the array of objects you're after.

  2. You shouldn't be adding the ''s around the string.

  3. data: "{}" is meaningless. You want it to either be a string of key=value pairs (foo=1&bar=2, like a query string), or an object ({foo:1, bar:2}), which jQuery turns into a jQuery string for you. In your case, you can omit the data attribute completely.

1 Comment

I was removing the [] because I tried to validate the json and it kept on coming up as invalid and it seemed that once I removed the brackets everything validated.
1

The problem is the following

myObj = "'" + myObj + "'";

JSON should not be surrounded by quotes.

You are also remove the [ ] characters, which will make it an array. However, as it stands, you'll want to split it and evaluate each piece instead of trying to process it all, because a raw array is not valid JSON.

4 Comments

It's also the fact he's removing the [ and ], because he's receiving an array of objects.
Missed the comma making it an array, so you are correct, but then it is not valid JSON. I'll edit
It's changing [{ /* object */ }, { /* object */ }] into { /* object */ }, { /* object */ }
Yeah, when I looked at first, I missed the comma and thought it was one object. I've noted that in my response now
0

Check out jsonlint.com to verify that your json is properly formatted before you try to parse it. The string you have in your comment under the "not working" version is not properly formatted - it needs to be wrapped in "[...]".

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.