When I have this kind of object:
myObj = {
accountNumber:"12345",
limit:"10",
offset:"0",
serviceProduced: {
min:"2015-03-01"
}
}
and I pass it via $http get as params:
$http({
url: '/foo'
method: 'GET'
params: myObj
});
for some reason it comes to server like this after its JSONified by $http:
{"accountNumber":"1191009461","limit":"10","offset":"0","serviceProduced":"{\"min\":\"2015-03-01\"}"}
How can I prevent the 'serviceProduced' not to be converted to string? So that it would be like this (correct):
{"accountNumber":"1191009461","limit":"10","offset":"0","serviceProduced":{"min":"2015-03-01"}}
I think you are miss using http get. It is not supposed to support nested objects.
It should be in the following format: ?accountNumber=1191009461&limit=10&...
However, if you want to achieve what you are looking for, you can configure your object to be like:
myObj = {
accountNumber:"12345",
limit:"10",
offset:"0",
"serviceProduced.min": "2015-03-01", // you should be able to handle this format server side.
// OR
"serviceProduced[min]": "2015-03-01"
}
try:
$http.get("#{url}", myObj)...
it should work.
Related
How would I serialize url parameters for use with axios? My parameters are just numbers in array [1,2]. Here is my code so far
axios({
method: 'delete',
url: '/api/'
})
My request url will be something like this http://127.0.0.1:8000/api/?id=1&id=2
I looked at the paramsSerializermethod that axios has but its confusing how it can be used or whether its even appropriate in my case. Please advice. Thanks
the config object of axios.get accepts params. In params you can specify your array and it will do the conversion for you.
Here is an example:
axios.get('/api/', {
params: {
id: [1,2]
}
})
This will make a request which looks like this:
/api/?id[]=1&id[]=2
This is only for debugging purpose. Only returning JSON, outputs unreadable JSON string on webpage. Is there any quick solution to view formatted json on webpage?
Looking for a C# function that will take json object and return formatted output as string from my action method.
Just change JSON global settings in your Global.asax file.
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
It should produce indented JSON for all your Web API endpoints.
Then you can inspect resulting JSON directly in browser or using some HTTP traffic capturing tool like Fiddler.
Use the JavaScript JSON.Stringify() function. Example:
$.ajax({
method: "POST",
url: "/yourController/yourAction",
data: { name: "John", location: "Boston" }
}).done(function( data ) {
alert(JSON.Stringify(data));
});
I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.
The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.
Here is the code:
index.html (snippet)
function getData() {
$.ajax({
url: 'http://127.0.0.1:3000',
dataType: 'json',
success: function(data) {
$("#results").html(data);
alert(data.engineURL); // alerts: undefined
}
});
}
server.js
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test.py']);
var resp = '';
child.stdout.on('data', function(data) {
resp = data.toString();
});
child.on('close', function() {
callBack(resp);
});
}
http.createServer(function(request, response) {
run(function(data) {
response.writeHead(200, {
'Content-Type':
'application/json',
'Access-Control-Allow-Origin' : '*' });
response.write(JSON.stringify(data));
response.end();
});
}).listen(PORT, HOST);
test.py
import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})
After the AJAX call comes back, I execute the following:
$("#results").html(data);
and it prints the following on the web page:
{“engineURL": "http://www.google.com", "engineName": "Google"}
However, when I try and parse the JSON as follows:
alert(data.engineURL);
I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?
Thanks.
I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:
data = $.parseJSON(data);
Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.
Also:
child.stdout.on('data', function(data) {
resp = data.toString();
// ^ should be +=
});
The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.
I am new to Backbones.js, and I was trying to get my JSON urls and parse them correctly.
This is my code:
window.Post = Backbone.Model.extend({
initialize: function(options) {
this.id = options.id;
},
url: function() {
return 'api/get_post/?post_type=movies&id=' + this.id;
},
parse : function(response) {
return response.posts;
},
});
window.Posts = Backbone.Collection.extend({
model: Post,
defaults: {
model: Post,
},
url: "api/get_recent_posts/?post_type=movies",
parse : function(response) {
return response.posts;
},
});
It seems that parsing for both overrides each other or something. when I remove the parse option from the Post class, I get a full response from the collection, but not from the model.
Are there any clear examples on how to set parsing for different son hierarchies? my JSON result have a status ok before it dives into the actual data.
I've never used bones.js but maybe these examples will help.
I think what you want to do is get rid of the parse() function in your collection. This assumes that since it is a Post collection, your data will come in as an array of Post JSON objects [{id:'1', 'sub':{data}},{id:'2', 'sub':{data}},{id:'3', 'sub':{data}}] or something like that.
If your Post model has sub-models or collections, your model parse() will then take the sub-object property name and do something with it.
// In Post Model definition
parse:function(response) {
if (response.sub) {
// create some model or collection etc.
}
}
You might have to pass an option parse:true when you do your collection fetch.
I posted something along these lines which might help you see how sub-models can be instantiated on fetch calls.
Backbone.js: Load multiple collections with one request
Cast/initialize submodels of a Backbone Model
I hope this helps.
I need to get Json data from a C# web service.
I know there are several questions based on this, trust me I have read through quite a few but only to confuse me further.
This is what I have done :
In my web service I have included : [System.Web.Script.Services.ScriptService] for the class & [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] for the method
I have also used a JavaScriptSerializer() to convert my data to a string
I am calling this service using $.getJSON()
If I don't use that I get an Cross domain reference error.
To do this I had to setup m service to get the callback function name
so I am passing this.Context.Request["callback"] + serialized Json Data;
But in the output I get it wrapped in
< string xmlns="http://XYZ...">
The data within the tags is in the format I need
I also tried setting content type using : $.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});
But still no success.
Addded later: I accepted frenchie's anwser beacuse I know it is the correct approach but I stil cud not get it to work... I just put the webservice & website in the same domain & used xml, I know it wasnt the best way, but I had spent 2 days on it & could not afford to waste more.
Use this:
var JsonString = ....;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "YourWebServiceName.asmx/yourmethodname",
data: "{'TheData':'" + JsonString + "'}",
dataType: "json",
success: function (msg) {
var data = msg.hasOwnProperty("d") ? msg.d : msg;
OnSucessCallBack(data);
},
error: function (xhr, status, error) {
alert(xhr.statusText);
}
});
function OnSuccessCallData(DataFromServer) {
// your handler for success
}
and then on the server side, in the code behind file that's auto-generated in your AppCode folder, you write something like this:
using System.Web.Services;
using System.Web.Script.Serialization;
[System.Web.Script.Services.ScriptService]
public class YourWebServiceName : System.Web.Services.WebService
{
[WebMethod]
public string yourmethodname(string TheData)
{
JavascriptSerializer YourSerializer = new JavascriptSerializer();
// custom serializer if you need one
YourSerializer.RegisterConverters(new JavascriptConverter [] { new YourCustomConverter() });
//deserialization
TheData.Deserialize(TheData);
//serialization
TheData.Serialize(TheData);
}
}
If you don't use a custom converter, the properties between the json string and the c# class definition of your server-side object must match for the deserialization to work. For the serialization, if you don't have a custom converter, the json string will include every property of your c# class. You can add [ScriptIgnore] just before a property definition in your c# class and that property will be ignored by the serializer if you don't specify a custom converter.