question about JSON - javascript

If I have in my db a table called User with name, Id, age fields and I want to get these data and put it in a var as a JSON serialize, then I want to send it to javascript page to reform it as I want . I need to know how to put these data in a var as a JSON, how to read the data in the javascript file (how to deal with each one. for example : array[name]) !!!?
which thing is more better to deal with these data in asp.net code then send it in the javascript or to send it to the javascript and then to deal with !!? thank u :D

If you have an object in .NET you can serialize it using the JavaScriptSerializer
List<User> myUsers = GetAllUsers();
string userJson = new JavaScriptSerializer().Serialize(myUsers);
This way you won't have to worry about escaping quotes or anything. Now that you have a string, you can feed that to your javascript:
var userJson = ... // the JSON string
var myUsers = JSON.parse(userJson);
The other way around, you may have a javascript object, that you want to pass to the server:
var myUsers = ... // a JS object
var userJson = JSON.stringify(myUsers);
If you pass the string userJson to the server, you can then deserialize it. If you know that the JS object corresponds entirely, in terms of property names, to a .NET object, or an array of .NET objects, say, you can deserialize it as such:
List<User> myUsers = new JavaScriptSerializer().Deserialize<List<User>>(userJson);
If there isn't a .NET object that can be directly mapped to the structure of the JS object, you'll have to use
object myUsers = new JavaScriptSerializer().DeserializeObject(userJson);

4guysfromrolla have great articles that will teach you the ins and outs of it.
https://web.archive.org/web/20210927191305/http://www.4guysfromrolla.com/articles/102010-1.aspx
https://web.archive.org/web/20211020203220/https://www.4guysfromrolla.com/articles/040809-1.aspx
you can take a look at these for your complete understanding.
besides if you just want to display results of a query ti the UI then why dont you use the gridview or repeater controls.

Related

Javascript Using Local Storage, calling back the object and changing with Json to a string to use in a populate function

Hello I am doing a form and I used a populate method to fill a form out in jJQuery (Yes I know jquery is just a library) for testing. Now I save the data in the form using Json and Local Storage. Then I call back the object in local storage and use Json to turn it back into a string. The problem is the string will be the EXACT same as the string i hard coded into the populate method but when I put the string to replace it (so its always using current form saved data) it will not work correctly. I'm assuming it is something small.
This is my object called back from local storage and turned back into a string.
var myString = localStorage.getItem("all");
var myStringSave = JSON.stringify(myString); //my string
myStringSave will contain for example:
Name:'Joe',dateBirth:'01/02/1992'
Which is the exact same as my hard coded one. However hardcoded works
$('#frm').populate({Name:'Joe',dateBirth:'01/02/1992'})
But the one in the string will not work:
$('#frm').populate(myStringSave)
or
$('#frm').populate({myStringSave})
I have been looking at it for a few hours and it makes no sense. The string is the exact same as my hard coded one, so why does it not work? Thank you any help is greatly appreciated.
populate accepts a JSON as parameter, and you give it a string.
The basic form for using Populate is: $(selector).populate(JSON,
options)
Don't do :
var myString = localStorage.getItem("all"); // this IS a string (localStorage can't store anything else)
var myStringSave = JSON.stringify(myString); // you stringify a string
You can get your JSON back by using :
myJsonSave = JSON.parse( localStorage.all )
Then $('#frm').populate(myJsonSave) should work.
You can even do it all in one line :
$('#frm').populate( JSON.parse( localStorage.all ) )

Converting JS object to json string using JSON.stringify

I have four textboxes which contain json string which I create by calling json.stringify on various js objects..
eg. '["users.name","users.username"]' (This is the value of one textbox)
What I want to do is create a single json string from these four json strings and send them to the backend using POST..
So I create a object and add them like this
tmp = {}
tmp["columns"] = $("#sc").val();
/*adding more data....*/
$.ajax("/api/backend", {
data: JSON.stringify(tmp),
/* more ajax code...*/
});
The data that gets sent is of the following format..
{"columns":"[\"users.name\",\"users.username\"]"}
This is not a string but a json object...
Now when I do the following..
tmp1= JSON.stringify(tmp)
and Post using..
$.ajax("/api/backend", {
data: JSON.stringify(tmp1),
/*more code below..*/
The data that gets sent is of the following format and is string..
"{\"columns\":\"[\\\"users.name\\\",\\\"users.username\\\"]\"}"
This string has a lot of '\' characters which needs to be taken into account in the backend.
Is this the right way of handling my problem or am I doing something wrong?
Thanks
It depends on what you are trying to achieve.
If you want to send to the server a JSON that combines all JSON in your inputs, you'd better parse the JSON in your inputs, prior to adding them to you tmp object. That way, you get an object containing objects, rather than an object containing JSON strings.
Retrieving JSON from inputs would be like this:
tmp["columns"] = JSON.parse($("#sc").val());
See that you are storing objects within your tmp object, rather than JSON strings. Then, you can just send that object as JSON to your server.
Thus, your server would receive this:
"{\"columns\":\"[\"users.name\",\"users.username\"]\"}"
Which, I believe, looks much better. I hope that helps.

JS: convert string into object

I have code
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
I want to convert it into JS object (not in JSON) and use it in this way:
data.newFavOfferId = ...
How can I do this?
If your source is trusted, the simplest solution is to use eval :
data = eval('('+data+')');
If you don't trust the source, then you'd better specify what you can have and parse the string manually (not terribly hard if you have only one level of properties for example).
Another solution (depending on your real data) would be to change your data into JSON by inserting the missing quotes :
data = JSON.parse(datareplace(/({|,)\s*([^:,}{]+)\s*(:)/g,'$1"$2"$3'));
just remove the quotes
data = {
isShowLoginPopup:true,
newFavOfferId:1486882
};
Fiddle: http://jsfiddle.net/QpZ4j/
just remove quotes "" from the
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
DEMO
Whilst on the surface this looks like JSON data, it's malformed and therefore it does not work directly with JSON.parse(). This is because JSON objects require keys to be wrapped in quotes...
therefore:
"{isShowLoginPopup:true,newFavOfferId:1486882}"
as valid JSON should be:
"{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}"
So what you have there in fact IS a JavaScript object, not JSON, however the problem you have is that this is a JavaScript object as a string literal. If this is hard coded, then you need to just remove the " from the beginning and end of the string.
var data = {isShowLoginPopup:true,newFavOfferId:1486882};
If this object is serialized and requires transmission from/to a server etc, then realistically, it needs to be transmitted as a JSON formatted string, which can then be de-serialized back into a JavaScript object.
var data = JSON.parse("{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}");

Saving javascript objects as strings

This is for a gaming application.
In my game I want to save special effects on a player in a single field of my database. I know I could just put a refrence Id and do another table and I haven't taken that option off the table.
Edit: (added information) This is for my server in node not the browser.
The way I was thinking about storing the data is as a javascript object as follows:
effects={
shieldSpell:0,
breatheWater:0,
featherFall:0,
nightVision:0,
poisonResistance:0,
stunResistance:0,
deathResistance:0,
fearResistance:0,
blindResistance:0,
lightningResistance:0,
fireResistance:0,
iceResistance:0,
windResistance:0}
It seems easy to store it as a string and use it using effects=eval(effectsString)
Is there an easy way to make it a string or do I have to do it like:
effectsString=..."nightVision:"+effects.nightVision.toString+",poisonResistance:"+...
Serialize like that:
JSON.stringify(effects);
Deserialize like that:
JSON.parse(effects);
Use JSON.stringify
That converts a JS object into JSON. You can then easily deserialize it with JSON.parse. Do not use the eval method since that is inviting cross-site scripting
//Make a JSON string out of a JS object
var serializedEffects = JSON.stringify(effects);
//Make a JS object from a JSON string
var deserialized = JSON.parse(serializedEffects);
JSON parse and stringify is what I use for this type of storatge
var storeValue = JSON.stringify(effects); //stringify your value for storage
// "{"shieldSpell":0,"breatheWater":0,"featherFall":0,"nightVision":0,"poisonResistance":0,"stunResistance":0,"deathResistance":0,"fearResistance":0,"blindResistance":0,"lightningResistance":0,"fireResistance":0,"iceResistance":0,"windResistance":0}"
var effects = JSON.parse(storeValue); //parse back from your string
Here was what I've come up with so far just wonering what the downside of this solution is.
effectsString="effects={"
for (i in effects){
effectsString=effectsString+i+":"+effects[i]+","
}
effectsString=effectsString.slice(0,effectsString.length-1);
effectsString=effectsString+"}"
Then to make the object just
eval(effectsString)

what javascript arrays/objects type to use?

In my ASP.NET page, I want to return some data from the client-side form, which is preferable to be stored as a dictionary object. Now, I'm not very sure what type of object to use in my JavaScript function, which once accessed from the code-behind on the server (through Request.Cookies/any other suggested alternate way), can then be used as a .NET dictionary object?
Currently I'm saving the data as a specifically formatted string and then, on the server, I'm splitting it into arrays to use it. So, I'm just eager to know a better and of course, neater way to do this?
You can use json to transfer the data - it works great in Javascript and is supported in .Net 4.0.
First store the data in a javascript object and stringify it:
var data = {}
data.name = "Joe";
data.age = 17;
// ... whatever else you do ...
// convert to string
var jsonString = JSON.stringify(data);
// ... put in cookie, or use ajax, or use something else to give it to .Net
Then on the .Net side, you can use System.Web.Script.Serialization.JavaScriptSerializer to convert the json to a Dictionary:
String jsonString = HoweverYouGetIt();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string,object> data = serializer.DeserializeObject(jsonString) as Dictionary<string,object>;
//you can now use (int)data["name"]
JavaScriptSerializer can be found in the System.Web.Extensions assembly which is only in .NET 4.0, but this question has other alternatives.
As for how to transmit the data - if it's a dynamic web app, use ajax. If it's a website that collects data throughout multiple pages, use cookies.
And as always, be sure to sanitize any inputs!

Categories

Resources