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);
}
});
}
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.
You have to parse JSON to get stuff which is inside it (You have
done this)
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
Related
I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});
I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.
You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});
$.ajax({
url: link, //https://www.linkedin.com/company/666511/
type: 'GET',
success: function (data) {
console.log(data)
//response comes in 2000 lines
here is the sample short response
["Web Development","Professional Training","Apprenticeship","Nonprofit"]
,
"companyPageUrl":"http://www.thedifferenceengine.io"
//i only want this link to return
http://www.thedifferenceengine.io
}
});
i dont understant what regex or jquery require or how i remove this "e and get companypageurl
you can use the regex
/http:[^;]+/
let str = '["Web Development","Professional Training","Apprenticeship","Nonprofit"],"companyPageUrl":"http://www.thedifferenceengine.io"'
console.log(str.match(/http:[^;]+/));
var decode ='["Web Development","Professional Training","Apprenticeship","Nonprofit"],"companyPageUrl":"http://www.thedifferenceengine.io"';
alert($("<div/>").html(decode).text());
var buttonOptions = {
gmap: map,
name: 'Download JSON File',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function () {
$.ajax({
type:"GET",
contentType: "application/json; charset=utf-8",
url: "getJSON.php",
data: "{}",
//dataType: 'json',
cache:false,
success: function(data){
}
});
}
}
I have a button that returns the JSON file below
[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]
My question is, how am I going to loop and display each field in the Success function? I tried using $.each to no avail. Also how can I count each value. I used $('#msg').html(data.length);, however it is counting each character in the JSON file, instead of the actual value. Thanks.
I used $('#msg').html(data.lenght);, but it is counting each character in the JSON file, instead of the actual value.
It's quite evident because you haven't parsed the JSON yet, so data is evaluated as a string here.
Solution:
You need to parse the JSON data before trying to access it. So your code need to be like this:
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
}
how am I going to loop and display each field in the Success function?
And then you can loop over dataafter it's parsed with .each():
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
data.each(function(){
//Your code here
});
}
Edit:
Another thing in your Ajax call why are you using url: "getJSON.php"? In that case the Ajax call will just load the content of the PHP file as a string.
In the URL you should put your .json file or a web service that returns a JSON string.
Demo:
Here's a Demo snippet showing the problem in details and where did 1610 came from in data.length :
var json = '[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]';
//logging json.length without parsing it
console.log('logging json.length without parsing it');
console.log(json.length);
var data = JSON.parse(json);
//logging data.length after parsing it
console.log('logging data.length after parsing it');
console.log(data.length);
As #chsdk said data is returned being as a string instead of a Javascript object you may want to take a look at $.getJSON() instead of $.ajax() for iterating over JSON objects
$.getJSON( "getJSON.php", function( data ) {
var count = data.length;
$.each( data, function( key, val ) {
//perform operations on data
});
});
http://api.jquery.com/jquery.getjson/
I have an ASP.Net MVC Application and I got a JSON response from the server using this code segment.
public JsonResult GetVehicleByID(string VehicleID)
{
db.Configuration.ProxyCreationEnabled = false;
var res = from type in db.Vehicles
where type.ID == VehicleID
select new
{
ID = type.ID,
RegNo = type.RegNo
};
return Json(res, JsonRequestBehavior.AllowGet);
}
The code above returns the following Json (Google Postman)
[
{
"ID": "000001",
"Type": "Internal"
}
]
I handled the response using following jQuery Ajax
function GetVehicle(id) {
$.ajax({
async: true,
url: "GetVehicleByID?VehicleID=" + id,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (data) {
//Parsing Method 1
//var a = jQuery.parseJSON(data);
//console.log(a.Type);
//Parsing Method 2
var b = $.parseJSON(data);
console.log(b['Type']);
}
});
}
I was unable to extract the Type element from this response. There are several similar questions in the Stack Overflow & solutions of those questions are about parsing. I tried to parse in 2 ways but the browser log gives following error
Uncaught SyntaxError: Unexpected token o in JSON at position 1
Helping is highly appreciated than flagging this question as duplicate.
Try just console.log(data[0].Type). I believe jQuery is already parsing the response as JSON for you because you specified dataType: "json" and the response from the server had the right Content-Type header.
As #smarx said jQuery already decoded json for you, so you can access directly to the Type from the data variable, but if not, you can parse the json response with the JS function parse:
var json_data = JSON.parse(data);
console.log(json_data);
I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array