I have a webservice that returns a JSON object, but when I try to loop through it, each item in each object returns undefined
Here is the JSON object returned from the webservice
[{"result":14,"question":"6 - 7 مرات اسبوعيا","aID":70},{"result":29,"question":"3 - 5 مرات اسبوعيا","aID":71},{"result":41,"question":"مرة واحدة اسبوعيا","aID":72},{"result":14,"question":"1 - 3 مرات شهريا","aID":73}]
and here how I loop through it:
var resultAsJson = data.d;
$.each(resultAsJson, function (index, resObject) {
$('#pollResults').append('<p><strong>' + resObject.result + ' ' +
resObject.question + '</strong></p>');
alert(resObject.question);
});
------------------
UPDATE
------------------
hi Guys,
the above code worked fine, the problem was the JSON response that I returned from the webservice was serialized as the following:
Dim m_result As New Data.Objects.ObjectParameter("Result", GetType(Boolean))
Dim lstofresult As List(Of addPollvote_Result) = Context.addPollvote(para_pid, para_aid, Date.Now, m_UID, Nothing, HttpContext.Current.Request.ServerVariables("REMOTE_ADDR"), Nothing, m_result).ToList
Dim m_json As New Script.Serialization.JavaScriptSerializer
Return m_json.Serialize(lstofresult)
When I removed the serialization and just returned the list, it worked perfect, see the below working code.
Dim m_result As New Data.Objects.ObjectParameter("Result", GetType(Boolean))
Dim lstofresult As List(Of addPollvote_Result) = Context.addPollvote(para_pid, para_aid, Date.Now, m_UID, Nothing, HttpContext.Current.Request.ServerVariables("REMOTE_ADDR"), Nothing, m_result).ToList
Return lstofresult
and it worked perfect.
Make sure resultAsJson is actually a JSON object and not a string and it should work (see this jsfiddle) - use resultAsJson = JSON.parse(resultAsJson) to do the conversion from string to json object .
Give this a go. I assume you're using jQuery:
// The JSON String from the web service
var jsonString = '[{"result":14,"question":"6 - 7 مرات اسبوعيا","aID":70},{"result":29,"question":"3 - 5 مرات اسبوعيا","aID":71},{"result":41,"question":"مرة واحدة اسبوعيا","aID":72},{"result":14,"question":"1 - 3 مرات شهريا","aID":73}]';
// Parse the JSON string into a JS object
var jsonObj = JSON.parse(jsonString);
// Loop through, and pull what you need from it
$(jsonObj).each(function() {
console.log(this.result + " " + this.question);
});
The problem seems to be your datasource.
I would use a 'for' loop for testing purposes:
var resultAsJson = data.d;
var resultAsJsonLength = resultAsJson.length;
for(i=0;i<resultAsJsonLength;i++) {
$('#pollResults').append('<p><strong>' + resultAsJson[i].result + ' ' +
resultAsJson[i].question + '</strong></p>');
alert(resultAsJson[i].question);
}
You're going to have to provide more information about how you're accessing the data, which seems to be the foundation of your problem...
Related
i have to send an array of objects like this
[{"Cod":"1"},{"Cod":"5"}]
to my C# WCF Service which i used until today without problems with wsHttpBinding (so no JSON using here, only XML).
The request, POST, contains this param:
let param = "<cod>" + data + "</cod>";
My problem is on WCF because i can't find a way to get that array of objects from the parameter of the method:
public string GetArrayOfObjects(CompositeType[] cod)
{//implementation not important because i can't enter here...}
where CompositeType is:
[DataContract]
public class CompositeType
{
string cod;
[DataMember]
public string Cod
{
get { return cod; }
set { cod = value; }
}
}
I have tried so many things like changing the parameter to:
Object[] cod
List<string> cod
...
Everytime i get this error (translating):
Exception generated by the formatter in an attempt to deserialize the message: Error trying to deserialize the parameter http://tempuri.org/:cod. InnerException: 'Error at line 1 position 341. Expected status 'Element' .. Found 'Text' with '' name space ''. '.
...
This is the post message that i'm sending:
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<s:Envelope xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\">" +
"<s:Header>" +
"<a:Action s:mustUnderstand=\"1\">http://tempuri.org/IService1/" + GetArrayOfObjects + "</a:Action>" +
"</s:Header>" +
"<s:Body>" +
"<" + GetArrayOfObjects + " xmlns=\"http://tempuri.org/\">" +
param +
"</" + GetArrayOfObjects + ">" +
"</s:Body>" +
"</s:Envelope>";
where param is defined before. The JSON.stringify of data inside param gives the first example of this question ([{"Cod":"1"},{"Cod":"5"}]). This post message was always fine with single value params.
Some sites show a solution with a json deserializer on wcf, but i'm using XML...it's not an option right now to re-implement the project in json.
I tried for one day but i didn't find a solution, i'd love to hear some solutions from you! Thanks to all.
I am trying to load a javascript in WebView to do some calculations and get the output in a string. I tried to use following code
string htmlFragment = "<html><head><script type='text/javascript'>" +
"function doubleIt(incoming){ " +
" var intIncoming = parseInt(incoming, 10);" +
" var doubled = intIncoming * 2;" +
" document.body.style.fontSize= doubled.toString() + 'px';" +
" return doubled.toString());" +
"};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
htmlView.NavigateToString(htmlFragment);
htmlView.LoadCompleted += async(s1,e1) =>
{
string result = await htmlView.InvokeScriptAsync("eval", new string[] { "doubleIt(25)" });
Debug.WriteLine(result);
};
Update
I am able to load simple javascript easily now based on help provided in the answer. But now I am facing issues when there is more than one function in javascript, I am getting an exception. I am trying the following code
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return 10;};" +
"function b(){return 20;};" +
"function c(){return 30;};" +
"return (a()*b()*c());" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
Please suggest.
The documentation for this feature is really poor. It took me some time to figure out how to invoke Javascript in UWP WebView
When you first look at the function call webView.InvokeScriptAsync(string,string[]) your initial reaction is that they want the function name as the first parameter and then the function paramaeters as the string array. (mainly because the MSDN documentation says this)
Parameters
scriptName
Type: System.String [.NET] | Platform::String [C++]
The name of the script function to invoke.
arguments
Type: System.String[]
[.NET] | Platform::Array [C++]
A string array that
packages arguments to the script function.
HOWEVER, this is wrong and will lead to hours of head banging. REALLY, what they want is the word "eval" in the first parameter and then a string array of functions, and or commands you wish to eval
var value = await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
Having worked with Microsoft APIs for a few years now I am convinced that this is not the intended way of consuming this function and is a bit of a hack. Unfortunately if you want to consume JavaScript this is the only way that I know that works currently.
Anthony,
Try to check your own suggestion:
await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
or:
await webViewer.InvokeScriptAsync(functionName, new string[]{ functionParameters });
The same as Microsoft suggests, just you are limiting a function name by one ("eval") - not necessary. Trust me, you can use any function name, as I am now with UWP and before with windows phone hybrid apps.
The question is already 4 years old, but I'm coming to see why you were getting an empty string as a result.
In your example, the functions in JavaScript return integers while the expected value is of type string.
By modifying these functions and returning a string like this:
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return '10';};" +
"function b(){return '20';};" +
"function c(){return '30';};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
We get the good result on the way back.
everybody. I've just integrated duktape in my c++ code so that I'm able to use javascript.
But the problem I can't solve right now : how to use json objects in javascript.
Assume I've got some javascript like
function hi(person) {
print ('hi, ' + person.name );
}
And json object :
{
'name' : 'duktape'
}
So now I need to call function hi with an argument of this json in my cpp code.
duk_eval_string(ctx, "function hi(person) {print ('hi, ' + person.name );}");
duk_push_global_object(ctx);
duk_get_prop_string(ctx, -1, "hi" ); // pushes function from loaded script to stack
auto json = "{'name' : 'duktape' }";
duk_push_string(ctx, json);
duk_pcall(ctx, 1);
The output I get tells, that object is not correct
hi, undefined
Would like to head any suggestions on who should be done to get it working! Thank's for your time :)
You need to use duk_json_decode:
char *json = "{\"name\": \"duktape\"}";
duk_push_string(ctx, json);
duk_json_decode(ctx, -1);
duk_pcall(ctx, 1);
duk_pop_2(ctx);
Output:
hi, duktape
Note that your original json is not valid, you need to use " as string delimiters instead of '.
Depending on what you really needs, you could also create the object manually:
duk_idx_t obj_idx = duk_push_object(ctx);
duk_push_string(ctx, "duktape");
duk_put_prop_string(ctx, obj_idx, "name");
duk_pcall(ctx, 1);
duk_pop(ctx);
Is it possible to convert mongo objectId into string.
The above pictures shows data i received and shown in console.I need id value in string form .but ObjectId is returning as object
In Database id is look like this- 565d3bf4cefddf1748d1fc5e -objectId and i need id exactly like this –
According to the Mongo documentation:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
You can check it out here: https://docs.mongodb.org/manual/reference/object-id/
So in javascript you could do something like this.
var mId = {
Timestamp:1448950573,
Machine:13565407,
Pid:1756,
Increment:8888962
};
function getId(mongoId) {
var result =
pad0(mongoId.Timestamp.toString(16), 8) +
pad0(mongoId.Machine.toString(16), 6) +
pad0(mongoId.Pid.toString(16), 4) +
pad0(mongoId.Increment.toString(16), 6);
return result;
}
function pad0(str, len) {
var zeros = "00000000000000000000000000";
if (str.length < len) {
return zeros.substr(0, len-str.length) + str;
}
return str;
}
console.log(getId(mId))
It produces "565d3b2dcefddf06dc87a282" which was not exactly the id you had, but that might just be a tweak or i was working with different data :D.
EDIT
Added a padding function so that zeros are not truncated.
Hope that helps
EDIT:
I assume you are using c# to connect to and serve documents from the mongo DB. In that case, there is a driver that also supports toString().
Here is an example using the mongo csharp driver:
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
// ...
string outputFileName; // initialize to the output file
IMongoCollection<BsonDocument> collection; // initialize to the collection to read from
using (var streamWriter = new StreamWriter(outputFileName))
{
await collection.Find(new BsonDocument())
.ForEachAsync(async (document) =>
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonWriter(stringWriter))
{
var context = BsonSerializationContext.CreateRoot(jsonWriter);
collection.DocumentSerializer.Serialize(context, document);
var line = stringWriter.ToString();
await streamWriter.WriteLineAsync(line);
}
});
}
ORIGINAL:
These are Mongo ObjectId's and if you haven't already deserialised the document they should support a toString method that will return a hexadecimal string.
but if you want this applied to the whole document, using JSON.stringify(MogoDocument) should deserialize this for you into a plain object.
Can anyone shed any light as to why my JSON is coming out below, with the extra backslashes. I am using ASP.net MVC to serialise a datatable, when I debug in Visual studio it all looks ok but when I look with firebug with adds the extra characters?
Any ideas anyone?
JSON
[{\"uid\":\"516219026\",\"pic\":\"http://profile.ak.net/\",\"first_name\":\"Daniel\",\"last_name\":\"James\",\"fql_query_response_Id\":0,\"LIFEID\":null}
JAVASCRIPT
function GetFBFriends() {
FB.Connect.requireSession(function() {
$.ajax({
url: "/Facebook/GetFaceBookFriends",
type: 'POST',
data: null,
dataType: 'json',
success: function(result) {
data = "<table>";
alert(result.length);
for (i = 0; i < result.length; i++) {
data += "<tr><td><td><img src=" + result[i].pic + " alt=" + result[i].first_name + " /></td><input type='checkbox' value='" + result[i].uid + "' name='friends[]' id = 'friend" + result[i].uid + "' /></td><td>" + result[i].first_name + " " + result[i].last_name + "</td></tr>";
}
data += "</table>";;
}
});
})
};
Public Function GetFaceBookFriends() As JsonResult
Dim fbFriends As New DataTable
Try
fbFriends = FacebookModel.GetFriendsAndMatchToLife()
Return Json(JsonConvert.SerializeObject(fbFriends))
Catch ex As Exception
Finally
fbFriends.Dispose()
fbFriends = Nothing
End Try
End Function
That's Firebug showing the string containing JSON in it's string representation. Think of it as JSON-encoding a string containing JSON. Or rather, if your were to put the JSON in a string literal in your Javascript, it would look like that.
Your string does not actually contain those backslashes. They are just escapes for the double-quotes.
Looks like Firebug is adding escape characters. What if you enclosed your entire JSON in single quotes? That may correct the problem. Edit Can you provide the code that encodes your JSON?
I solved this question, I was returning JSON data which was then being changed into JSON by jquery as well, so I simply returned a string and jquery handled it correctly.
I would suggest doing injecting the following into the first line for the success function.
console.dir({'result':result});
This will show you what you are getting back, as opposed to just viewing the result from the network call.
The Firebug display is simply escaping the string, so you can copy/paste the entire result into the console for inspection/interrogation directly...
var temp = {pasted-string-here}
//var temp = "[{\"uid\":\"516219026\",\"pic\":\"http://profile.ak.net/\", ... }]"
var val = JSON.parse(temp);
console.debug({"val":val});