0

Hello and thank you for the time you are taking to look at this.

The problem I am having is with a JSON return from a third party service so I have no control over how the JSON is formatted. I am using the following (stripped down to the important pieces)

function JSONgrabber(Zip,iplocation)
        {
            var requestBase ="http://www.someCompany.com/api/request";
            var requestData ="iplocate=true&output=json&callback=useJSON";

            var request=requestBase+"&&zip="+Zip+"&"+requestData;
            if(iplocation ==false || iplocation=="false")
            {
                request=request.replace("iplocate=true","iplocate=false");

            }
            if (document.getElementById("JSONDataMaster"))
            {
                var element = document.getElementById("JSONDataMaster");
                element.parentNode.removeChild(element);
            }
            try{
            var head = document.getElementsByTagName("head").item(0);
            var script = document.createElement("script");
            script.setAttribute("type", "text/javascript");
            script.setAttribute("src", request);
            script.setAttribute("id", "JSONDataMaster");
            head.appendChild(script);
            }
            catch(err){console.log("Problem loading JSON Data");}
            }
        function useJSON(JSONDATA){}

This works 99% of the time just as expected but on occasion the return has something like

Joe's Diner and the ' causes a Uncaught SyntaxError: Unexpected identifier, this happens during the return so I have not been able to work with it via replace etc to fix it as it never gets to the callback function.

any insight is much appreciated. I am not using any outside libraries (jquery etc) so please any help needs to be pure JS (perhaps php)

1 Answers1

0

you need to check whether the string you want to get contains special chars and if so you need to escape them

this is a good page that can help to understand:

art of the web

this issue is similar:

stacko

if you check every string for a single quote and replace it with the escaped single quote:

mystring.replace("'","\\'");
Community
  • 1
  • 1
p0rter
  • 961
  • 2
  • 13
  • 28
  • Can you show me an example of how to do so in this case? I do escape them for things like \n \t etc once I get the string the problem I am having is I cannot evaluate the string since it errors out during the return. – Noel Proulx May 09 '12 at 13:01