0

I have a JSON response as the follwoing, but my problem is there are some characters that is not related to the JSON response I want. So I have pass that JSON response to a JavaScript variable and look into the JSON string. That is at the bottom.

-----------JSON Response------------

{
   "readyState":4,
   "responseText":"<?xml version=\"1.0\"encoding=\"utf-8\"?>\r\n<string>{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:76546294&dimensions=ga:userType&metrics=ga:users&start-date=2014-10-01&end-date=2014-10-23&max-results=10\",\"query\":{\"start-date\":\"2014-10-01\",\"end-date\":\"2014-10-23\",\"ids\":\"ga:76546294\",\"dimensions\":\"ga:userType\",\"metrics\":[\"ga:users\"],\"start-index\":1,\"max-results\":10},\"itemsPerPage\":10,\"totalResults\":2,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:76546294&dimensions=ga:userType&metrics=ga:users&start-date=2014-10-01&end-date=2014-10-23&max-results=10\",\"profileInfo\":{\"profileId\":\"76546294\",\"accountId\":\"289147\",\"webPropertyId\":\"UA-289147-1\",\"internalWebPropertyId\":\"456104\",\"profileName\":\"US - Institutional Investors - NP Microsite\",\"tableId\":\"ga:76546294\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:userType\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:users\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:users\":\"1110\"},\"rows\":[[\"New Visitor\",\"826\"],[\"Returning Visitor\",\"284\"]]}</string>",
   "status":200,
   "statusText":"OK"
}

-----------End of JSON ------------

I want to remove these characters from the beginning of the string:

`{"readyState":4,"responseText":"<?xml version=\"1.0\"encoding=\"utf-8\"?>\r\n<string>`

And I want to remove these character from the end of the string:

`</string>","status":200,"statusText":"OK"}`

So I want to remove these characters. I think a set of JavaScript String functions to be used. But I don't know how to mix them and use.

Could someone help me to solve this matter?

Thanks and regards, Chiranthaka

UPDATE

I have used the follwoing AJAX function to send and get the JSON response back.

function setJsonSer() {
                formData = {
                'Email': 'clientlink@site.com',
                'Password': 'password1234',
                'URL': getVaria()
            };
                $.ajax({
                url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
                type: 'POST',
                data: formData,
                complete: function(data) {
            var jsonResult = JSON.stringify(data);
            alert(JSON.stringify(data));

            Load(data);

                }
            }); 
    }

UPDATE 02

function setJsonSer() {
                formData = {
                'Email': 'clientlink@russell.com',
                'Password': 'russell1234',
                'URL': getVaria()
            };
                $.ajax({
                url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
                type: 'POST',
                data: formData,
            dataType: 'json',
                complete: function(data) {
            var jsonResult = JSON.stringify(data);

            alert(jsonResult);

            Load(data);

                }
            });                 

    }
ChiranSJ
  • 195
  • 1
  • 3
  • 20
  • What is the object you are trying to send as JSON response? – Rey Libutan Oct 23 '14 at 03:33
  • Why have you converted your XHR object to JSON? Just use `xhr.responseText` to get the response portion. – Barmar Oct 23 '14 at 03:35
  • You need to parse `xhr.responseText` as XML, then get the `` element from it, and parse that as JSON to get what you want. – Barmar Oct 23 '14 at 03:37
  • See the UPDATE. But I haven't converted my XHR object to JSON but I used a 3rd party to build that JSON web service. I think the error is from their end then. So can we do anything from our end to solve this problem? – ChiranSJ Oct 23 '14 at 03:50
  • @CHiranSJ in your `$.ajax` call add `dataType: 'json'` and see if that makes things easier. Right now you're getting XML. Not sure if that's just on their end. If it turns out you can only retrieve XML, jQuery has a [`$.parseXML()`](http://api.jquery.com/jquery.parsexml/) function. Or you can simply [parse xml with javascript](http://stackoverflow.com/questions/7949752/cross-browser-javascript-xml-parsing) – aug Oct 23 '14 at 03:53
  • See the UPDATE 02. I have added `dataType: 'json'` to my $.ajax but the result was the same. I cannot understand how to solve this matter? – ChiranSJ Oct 23 '14 at 04:13
  • Don't embed xml in json. There be dragons. No really - don't. Just use responseText for what it sounds like. No need to wrap that in an xml telling you it's a string? – AlexanderBrevig Oct 23 '14 at 04:23
  • There is XML in the JSON. This is like trying to wrap an Apple inside an Orange Peel. Why does it need to be done this way? – Sukima Oct 23 '14 at 04:27
  • 1
    Actually that XML wrapping is not done by me it's done by the other party who have created this JSON web service. But now I want to remove that. – ChiranSJ Oct 23 '14 at 04:39
  • I believe you missed the second part of what I said. It seems they are only sending you XML so you simply need to parse it. I put links how to parse XML. Worst-case scenario, you can just do a `.split()` on `` and `` and convert the text inside into a JSON object with `JSON.parse()` – aug Oct 23 '14 at 06:56
  • Ok guys the problem solved. Thanks anyway. – ChiranSJ Oct 23 '14 at 07:25

2 Answers2

2

I looked at your code:

complete: function(data) {
  var jsonResult = JSON.stringify(data);

  alert(jsonResult);

  Load(data);
}

So you want to stringify your customized result, but your result is not well parsed JSON*? If yes then:

complete: function(data) {
  var responseText = data.responseText;
  var responseJson = JSON.parse(responseText.match(/[{].*.[}]/));
  // you can skip `JSON.parse` if you dont want to leave it as `String` type

  alert(JSON.stringify(responseJson)); //or just `responseJson` if you skip `JSON.parse`

  Load(JSON.stringify(responseJson));
}

This can solve your problem for a while. But I think the problem is in your backend which did not serve well parsed JSON data. My recommendation is fixing your backend system first.

*Not well parsed JSON because your result some kind of including XML type of string under JSON object.

Andi N. Dirgantara
  • 2,050
  • 13
  • 20
  • So all I want to remove that XML from my JSON response. To do that I am trying to use some JavaScript String Functions. But I cannot understand how to do that. I already passed the JSON to a JavaScript string variable called `jsonResult`. – ChiranSJ Oct 23 '14 at 04:38
  • Already tried my example? It can do what you expect with regex. But it's not good design, which your data is confused because it has `JSON` under `XML` under `JSON`. You can also parse the `XML` with `XML` parser instead of regex. It's up to you. – Andi N. Dirgantara Oct 23 '14 at 05:33
  • Andi's answer solved the problem and many thanks for Andi. I'm thanking to other friends also to help on thins matter. – ChiranSJ Oct 23 '14 at 07:27
  • 1
    Your answer is life savior still after 6 years . thanks a lot . you highlighted that instead of removing garbage characters extract the actual JSON from string and leave the invalid characters behind excellent sir . .it helped me a lot and saved my time none of the other solutions were working. – Zain Ul Abidin Jul 01 '21 at 07:31
0
  1. You have to parse JSON to get stuff which is inside it (You have done this)
  2. You have to parse the XML to get text which is inside the XML

Here's sample code for XML parsing: http://www.w3schools.com/xml/tryit.asp?filename=tryxml_parsertest2

Teddy
  • 4,009
  • 2
  • 33
  • 55