MVC - model to a json object - json

I had a mvc object as my model.
I need to stringfiy my model as a json object type - and then use it in js as i please.
i currently doing something like this
<script type="text/javascript">
$(function () {
var jsonData2 = '#Html.Raw(Json.Encode(Model))';
showBeginDate(jsonData2);
});
</script>
But when i try to acess a json property for exemple as jsonData2.BeginDate I keep getting undefined.
jsonData2 is a json object - why can i "read" from it?
Regards

#riteshmeher 's suggestion is correct
var text = '#Html.Raw(Json.Encode(Model))';
var obj = JSON.parse(text);
I don't know your model so I created a simple model with 2 attributes: Id and Name. In case that the model is a list, you can read it:
// Access to object in position 1
var result = obj[0].Id + " - " + obj[0].Name;
In other case, access right to the property.
var result = obj.Id + " - " + obj.Name;
For more info, check this post:
http://www.w3schools.com/js/js_properties.asp
http://www.w3schools.com/json/tryit.asp?filename=tryjson_parse
UPDATE
like #Stephen Muecke said, better this:
var obj = #Html.Raw(Json.Encode(Model));
var result = obj[0].Id + " - " + obj[0].Name;
thank #Craig for the corrections

Related

The array does not output properly

let test = [];
d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' + data.branch_nm + '</div>';
test.push(obj);
}
});
console.log(test);
console.log("test[0] : " + test[0]);
console.log("test.length : " + test.length);
[enter image description here][1]
I made the csv file into an object array.
And as a result of outputting the array, the array was output well,
enter image description here
but when outputting index 0, undefined came out and the length of the array was also 0.
It was printed properly when it was printed from the console.
What's the problem?
enter image description here
Without a jsfiddle or sandbox to play with, I can't tell exactly what is going on, but what I believe is happening is a mix of two things:
d3.csv is an async function, and therefore returns a promise.
The function you pass on to d3.csv is supposed to tell the function how to parse every element in the csv, and should return the parsed object, not add it to an external array or anything like that. Every element you return in that function will be an element in your resulting array
There's (at least) two possible ways you can deal with this:
await the async function, and its return value will be your required value, something like
const test = await d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' + data.branch_nm + '</div>';
return obj;
}
});
console.log(test);
console.log("test[0] : " + test[0]);
console.log("test.length : " + test.length);
Notice that here the function you pass onto d3.csv returns the object in the way you want to format it!
Do your logic in a .then statement, which also waits for the promise to be fulfilled:
d3.csv("cgvList.csv", function (data) {
if (data.poi_nm == "CGV") {
let obj = {};
obj.content = '<div>' + data.branch_nm + '</div>';
return obj;
}
}).then((test) => {
console.log(test);
console.log("test[0] : " + test[0]);
console.log("test.length : " + test.length);
});

How to get dynamic object properties

I'm receiving a Json object from a request and I would like to Iterate over its properties and do something like:
if property is equals to "EN" than get it's value.
The solutions That I saw in the web are all related with GetProperties/GetProperty methods but I tried both and none of them worked.
This should be something "simple" but I think that I'm missing something here.
//Deserializing the object
ExpandoObject deserializedContent = JsonConvert.DeserializeObject<ExpandoObject>(obj.ToString(), new ExpandoObjectConverter());
dynamic deserializedDynamicContent = deserializedContent;
//Tries
var value = deserializedDynamicContent.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
var value = deserializedDynamicContent.GetType().GetProperty("ES").GetValue();
in both cases I get zero properties.
I can only get the values if I do the code below, but this will obly me to code if a new language is added.
deserializedDynamicContent.EN,
deserializedDynamicContent.ES or
deserializedDynamicContent.PT
What Am I doing wrong here?
{
"EN":[{"Id":1,"Name":"One"},{"Id":2,"Name":"Two"},{"Id":3,"Name":"Tree"}],
"ES":[{"Id":1,"Name":"Uno"},{"Id":2,"Name":"Dos"},{"Id":3,"Name":"Tres"}],
"PT":[{"Id":1,"Name":"Um"},{"Id":2,"Name":"Dois"},{"Id":3,"Name":"TrĂªs"}]
}
I'm not sure exactly what you're trying to achieve, but since ExpandoObject implements IDictionary<string,object> you should be able to do something like this:
var expando = JsonConvert.DeserializeObject<ExpandoObject>(yourJson);
var dict = (IDictionary<string, object>)expando;
// look for a particular key...
object value;
if (dict.TryGetValue("EN", out value))
{
Console.WriteLine("Key exists!");
var list = (List<dynamic>)value;
Console.WriteLine(string.Join(",", list.Select(x => "{" + x.Id + "," + x.Name + "}")));
}
// or enumerate the entire dictionary...
foreach (var kvp in dict)
{
var list = (List<dynamic>)kvp.Value;
Console.WriteLine(
kvp.Key + ":" + string.Join(",", list.Select(x => "{" + x.Id + "," + x.Name + "}")));
}

How to access name of key in dynamically created json in action script 3

I have a json object coming from my java code as string :
{
"ABC":["ABC","XYZ","pqr"],
"OMG":["ABC","XYZ","pqr"],
"Hello":["ABC","XYZ","pqr"]
}
on decoding it as
myObj : Object = JSON.decode(result);
Now how do I access key names like ABC, OMG, HELLO...??
Try this will help you.
When you want properties in object use for-in loop or you want value use foreach statement.
var obj:Object = {
"ABC":["ABC","XYZ","pqr"],
"OMG":["ABC","XYZ","pqr"],
"Hello":["ABC","XYZ","pqr"]
};
var jsonText:String = JSON.stringify(obj);
var jsonObj:Object = JSON.parse(jsonText);
for(var key:String in jsonObj){
Alert.show("Key is"+key + " value is "+ jsonObj[key]);
}
Your case exactly
var myObj:Object = JSON.decode(result);
for(var key:String in myObj){
Alert.show("Key is"+key + " value is "+ myObj[key]);
}

Pass parameter to another page to generate listview from Json

Hello I'm using this js to pass the url parameter and it's working just fine, but my problem is that when I define the path to the JSON file I don't want to use the id of the item...I want to use another Id. For example: I have the following item:
{"id":"1",
"name":"Winery",
"street":"Chile",
"number":"898",
"phone":"4204040",
"mail":"winery#hotmail.com",
"web":"www.winery.com",
"lat":"-32.891638",
"long":"-68.846522",
"id_localidad":"1",
"id_provincia":"1"}
I want to put id_localidad at the end of the path, to generate the listview depending on the city (id_localidad is the id of the city where the shop is), not the id of the item. And this is not working for me.
Thanks in advance!
JS FILE
$('#PuntosDeVenta').live('pageshow',function(event){
var id = getUrlVars()["id"];
$.getJSON('http://localhost/CavaOnline/json_PuntosDeVentas.php?id_localidad='+id, function(vinerias) {
//THIS IS NOT WORKING, IS THE SAME AS PUTTING id, not id_localidad
$.each(vinerias, function(index, vineria) {
$('#listviewVinerias').append( '<li><a href="FichaTecnicaVineria.php?id=' + vineria[id - 1].id + '" > ' +
'<img src="pics/' + vineria[id - 1].img_url1 + '"/>' +
'<h4>' + vineria[id - 1].name+'</h4>' +
'<p>' + vineria[id - 1].street+ ' ' + vineria[id - 1].number+ '</p>' +
'</a></li>');
$('#listviewVinerias').listview('refresh')
});
});
});
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Div where I load the List
<div data-role="content">
<ul id="listviewVinerias" data-role="listview"></ul>
</div>
So I'm assuming your vinerias is a variable containing a list of JSON objects, even though I don't know why you are calling [id-1] everywhere.
If so, you can use the .filter() function to filter out the elements that have an id_localidad equal to the one specified.
var filteredVinerias = vinerias.filter(function(index){
return this["id_localidad"] === "1" //The localidad you want
});

Parsing a string, using action script

I am working on a flex site,
I want to parse the string below:
http://virtual.s1.c7beta.com/rpc/raw?c=Pictures&m=download_picture&key=a4fb33241662c35fe0b46c7e40a5b416&session_id=2b7075f175f599b9390dd06f7b724ee7
and remove the &session_id=2b7075f175f599b9390dd06f7b724ee7 from it.
How should i do it.
also later on when i get the url from database without session_id, i will attach the new session_id to it. Please tell me how to do that too.
Regards
Zeeshan
Not the short version but you can use URLVariable to get all the field(name, value) into an object and then add or delete any field you want.
Separate url and query:
var url : String = "http://virtual.s1.c7beta.com/rpc/raw?c=Pictures&m=download%5Fpicture&key=a4fb33241662c35fe0b46c7e40a5b416&session%5Fid=2b7075f175f599b9390dd06f7b724ee7";
var idxQMark : int = url.indexOf("?");
var qry : String = "";
Build url variable from query
var uv : URLVariables = new URLVariables();
if (idxQMark > 0) {
qry = url.substr(idxQMark + 1);
url = url.substr(0, idxQMark);
uv.decode(qry);
}
NOw you can access whatever field you need or delete them
delete uv.session_id;
Rebuild the query when needed
qry = uv.toString();
// get back you new URL
if (qry != "") {
url = url + "?" + qry;
}
For URI parsing check out the URI class provided in as3corelib.
http://code.google.com/p/as3corelib/source/browse/trunk/src/com/adobe/net/URI.as
For your specific case, you can clear the parts of the URI you don't want.
var url : String = "http://virtual.s1.c7beta.com/rpc/raw?c=Pictures&m=download%5Fpicture&key=a4fb33241662c35fe0b46c7e40a5b416&session%5Fid=2b7075f175f599b9390dd06f7b724ee7";
var uri : URI = new URI(url);
uri.query = "";
uri.fragment = "";
var shortenedUrl : String = uri.toString();
Or if you know you want to construct your url from just the scheme, authority, and path (i.e., you don't need to preserve port, username, password, etc.) you can build the url from parts.
var shortenedUrl : String = uri.scheme + "://" + uri.authority + "/" + uri.path;
If you're not sure that sessionid will be last you could split on the & using the as3 string.split functionhttp://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/String.html#split%28%29
then rebuild the string using a for loop leaving out strings that start with session_id using the string.indexOf function http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/String.html#indexOf%28%29 to see if "session_id" is at index 0
You can use regular expressions in Flex ... here's an example.
Assuming the session ID will always be the last variable in the query string:
var newStr:String = myStr.slice(0, myStr.indexOf("&session"));