1

I have looked at all similar questions to mine but cannot find any obvious errors in my code or my JSON string.

The script sends a request to a web service, which returns a JSON formatted string. Somehow, html related to debugging is getting tacked onto the end of the JSON string, so I remove it with the string.slice method, to return only the content between the opening and closing square brackets. When I output the slice, everything is there. When I check the resultant slice for proper JSON formatting in jsonlint, it passes. But when I try to parse the string and create an alert of the parsed data, I get an error: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ) at XMLHttpRequest.request.onload

Here is the JSON string after slicing, taken directly from the jsonlint output:

[{
    "user_id": "23",
    "name": "Steven Marsden",
    "email": "[email protected]",
    "password": "$2y$10$FjDZAugd2Mj9tw.z8U1mWexLF0vkD7jnB5xusGyClDUXZwQC6u9iy",
    "address": "2639 Valley Rdg Rd, Blairmore, AB T0K 0E0, Canada",
    "lat": "49.617134",
    "lng": "-114.388893",
    "created_at": "2021-06-06 18:00:20",
    "updated_at": "2021-06-06 18:00:20",
    "services": [{
        "u_s_id": "2",
        "user_id": "23",
        "mode": "seek",
        "service": "pet sitting",
        "details": "I have a dragon",
        "img_file": null
    }, {
        "u_s_id": "3",
        "user_id": "23",
        "mode": "offer",
        "service": "pet sitting",
        "details": "I love dragons",
        "img_file": null
    }, {
        "u_s_id": "7",
        "user_id": "23",
        "mode": "offer",
        "service": "pet foster home",
        "details": "Is it okay if my dragon eats your pet?",
        "img_file": null
    }],
    "color": "red"
}]

Here is the javascript that requests the string and tries to parse it:

        var url = 'http://localhost/helpinghands/public/index.php/services/getUsers';//Gets all users, complete with services offered and the appropriate marker color
    var request = new XMLHttpRequest();
    request.open('GET',url);
    request.onload = function(){
        if(request.status === 200){
            var resp = request.responseText;
            var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1);//Cleaves any extraneous info from end of string to avoid JSON parse errors
            var data = JSON.parse(slice);
            //var userLat = Number(data[0].lat);           
            alert(data);
                
            //var userLong = Number(data.lng);
            //const loc = new point(userLat,userLong);//This is the location from the database for that user
            

            //create marker object for loc by passing Marker constructor references to the loc and map objects, which are assigned to position and map variables, respectively 
            //const marker = new google.maps.Marker({map: map,position: loc, title: data.name});
      }
    };

Can anyone help me out?

Here is the output from the web service:

[{
    "user_id": "23",
    "name": "Steven Marsden",
    "email": "[email protected]",
    "password": "$2y$10$FjDZAugd2Mj9tw.z8U1mWexLF0vkD7jnB5xusGyClDUXZwQC6u9iy",
    "address": "2639 Valley Rdg Rd, Blairmore, AB T0K 0E0, Canada",
    "lat": "49.617134",
    "lng": "-114.388893",
    "created_at": "2021-06-06 18:00:20",
    "updated_at": "2021-06-06 18:00:20",
    "services": [{
        "u_s_id": "2",
        "user_id": "23",
        "mode": "seek",
        "service": "pet sitting",
        "details": "I have a dragon",
        "img_file": null
    }, {
        "u_s_id": "3",
        "user_id": "23",
        "mode": "offer",
        "service": "pet sitting",
        "details": "I love dragons",
        "img_file": null
    }, {
        "u_s_id": "7",
        "user_id": "23",
        "mode": "offer",
        "service": "pet foster home",
        "details": "Is it okay if my dragon eats your pet?",
        "img_file": null
    }],
    "color": "red"
}]
8
  • 5
    What is this doing??? var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1) Commented Jun 16, 2021 at 0:10
  • 1
    You just gotta post a raw response http://localhost/helpinghands/public/index.php/services/getUsers as shown in your browser's network tab. Commented Jun 16, 2021 at 0:11
  • 2
    never use alert. If you want to know what something looks like, use console.log and read your dev tools console. Alert is an ancient, obsolete function that neither you, nor anyone else, has any business with anymore. Also, modern JS has fetch(), absolutely use that instead of the (slighly less, but still very much) ancient XMLHttpRequest. Commented Jun 16, 2021 at 0:11
  • 1
    That output from the web service is exactly the same as what you say the slice returns. The slice would return a subset of that with invalid JSON Commented Jun 16, 2021 at 0:16
  • 2
    It's a really bad idea to try to "fix" JSON with string manipulation. Parse the whole thing, then you're working with a JavaScript object and you can do whatever you want. Commented Jun 16, 2021 at 0:19

1 Answer 1

1
var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1)

This function applied to your example JSON will cut off everything after the first ], which is the array nested under services, meaning that the first object in the json array will end up unclosed, as well as the json array that wraps the whole response.

You should fix the error in the server that returns HTML inside a JSON payload.

If that's not do-able, then you will need to detect the start of the HTML and cut there, though you are likely to keep experiencing more errors as a result of this faulty server endpoint

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.