injecting strings in json objects - javascript

In java script I create a json var
var Token = { "TagItem": { "TagList": [tags] } };
where tags is
"AA","BB","CCC","DDDD"
I call an asp mvc controller using ajax and I send the json to a method.
the desirialized json object is
public class TagItem
{
public List<string> TagList { get; set; }
}
and it is deserialized in ajax call to list with a single value of ["AA","BB","CCC","DDDD"].
instead of many values as if I would have writted
var data = { "tagItem": { "TagList": ["AA", "BB", "CCC", "DDDD"]} };
Which works great.
Idea on how to write it in js?

[tags] will create an array with only one element, tags.
If tags is a comma separated string like "AA,BB,CCC,DDDD", then you can use .split to transform it into an array.
var Token = { "TagItem": { "TagList": tags.split(',') } };
UPDATE: After seeing the screenshot you posted (http://i.imgur.com/IzSGS8L.png), I see what the real error here is. It's how you are creating tags.
You don't need to add ", or ,. You are just building an array/an object, you are not building a string. .map returns you an array, no need to convert it a string using .join, just use it as an array.
var tags = $('#myTags input[name="tags"]').map(function(){
return $(this).val();
}).get();
var Token = { "TagItem": { "TagList": tags } };
Note: There are no [] around tags. That's because it's already an array, no need to add it to another array.

Related

JavaScript selecting Object Arraylike?

The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name

How do I convert a C# object into a Javascript array of arrays using JSON?

I'm trying to convert an object of the following C# class type into a Javascript array of arrays:
public class SankeyData
{
public string Source { get; set; }
public int Width { get; set; }
public string Destination { get; set; }
}
The array of arrays in Javascript needs to look like this:
[["Link1",10,"Link2"],["Link3",20,"Link4"],["Link5",30,"Link6"]]
Is there an easy way to do the conversion? I'm using a jQuery $.getJSON to get the data from a C# controller action.
My related technologies include MVC5, jQuery, and JSON. I've tried using JSON.stringify and JSON.parse, but the data won't come over correctly.
Here's what I have so far:
$.getJSON('/Application/Sankey', { id: #Model.ID }, function (data) {
$.each(data, function (i, item) {
sankey.setData(JSON.stringify(item));
});
});
Which gives a close result, but not quite what I need:
[{"Source":"Link1","Width":10,"Destination":"Link2"},{"Source":"Link3","Width":20,"Destination":"Link4"},{"Source":"Link5","Width":30,"Destination":"Link6"}]
NOTE: I'm already using an MVC #model for something else in the page so I can't just set the #model to the SankeyData class.
There is no direct way out there to serialized C# objects to JSON Array. You can achieve this either
By converting C# objects to C# Array and then serialise the array as JSON.
Use Javascript to convert serialised objects to JSON Array.
I would recommend second option as array is heterogeneous.
Something like this:
function objectsToArray(data, columns) {
var dataArray = [];
for (var i in data) {
var itemArray = [];
for (var j in columns) {
itemArray.push(data[i][columns[j]]);
}
dataArray.push(itemArray);
}
return dataArray;
}
data = [{"Source":"Link1","Width":10,"Destination":"Link2"},{"Source":"Link3","Width":20,"Destination":"Link4"},{"Source":"Link5","Width":30,"Destination":"Link6"}]
console.log(objectsToArray(data, ["Source", "Width", "Destination"]));
So, just pull data using $.getJSON and the feed to objectsToArray with key names in order. Hope that solves your problem.

Get a JSON result based on a Ilist<int> in MVC

I need to build a string like "1-2-3-4-5", from an IList< int > returned by an MVC Action.
Action:
public virtual JsonResult AdvancedSearch(AdAdvancedSearchViewModel asViewModel)
{
IList<int> adIds = new List<int>();
try
{
var asDto = Mapper.Map<AdAdvancedSearchViewModel, AdAdvancedSearchDto>(asViewModel);
adIds = _adService.AdvancedSearch(asDto);
}
catch
{
adIds = null;
}
return Json(adIds);
}
Javascript function that processes the result:
function onAdAdvancedSearchSuccess(jsonAdListIds)
{
$("#adAdvancedSearchListForm #ids").val(jsonAdListIds);
}
The problem is that I get a string like this "[1,2,3,4]" in the "#adAdvancedSearchListForm #ids" HTML input, and I need to get "1-2-3-4", any idea?
Thanks.
If you want to do it at the client side, simply iterate throught the result array and build the string you want.
$.getJSON("yourURL", { Name: "John", Loc: "2pm" },function(result){
var str="";
$.each(result,function(i,item){
str=str+"-"+item;
});
alert(str);
});
Assuming Name and Loc are the properties of your viewmodel.
If you want to do it on the server side, you may use String.Join method to build the string representation you want. You may need to update the return type of your action method.
public string AdvancedSearch(AdAdvancedSearchViewModel asViewModel)
{
List<int> adIds = new List<int>();
//fill the list
var resutlStr= String.Join("-",adIds.ToArray());
return resutlStr;
}
I prefer to keep my action method returns JSON result instead of this string represetnation because an action method which returns JSON can be used in many places compared to this concrete string return implementation.
AJAX is returning an array which is expected since you are converting a list.
Try parsing the array into the string:
var r = jsonAdListIds[0];
for (var i = 1; i < jsonAdListIds.length; i++) {
r += '-' + jsonAdListIds[i];
}

Better way to build JSON array and retrieve its elements

Here's how I'm initializing and building an array:
var newCountyInfo = new Object();
newCountyInfo.name = newCountyName;
newCountyInfo.state = newCountyState;
newCountyInfo.zips = newCountyZips;
newCountyInfo.branchID = newCountyBranchID;
So I have my four elements in the array. I'm then passing newCountyInfo to another function to pull out the elements for display in some HTML elements.
The only way I know how to get to the individual elements in the function that uses them is this:
JSON.parse(JSON.stringify(newCountyValidation)).name
JSON.parse(JSON.stringify(newCountyValidation)).state
... etc...
There's got to be a better/shorter/more elegant way of doing this!
What is it?
Why are you serializing at all? I don't understand what JSON has to do with this, unless you're using web workers, ajax, or something else which demands serialization. Start with object literal syntax:
var newCountyInfo = {
name: newCountyName,
state: newCountyState,
zips: newCountyZips,
branchID: newCountyBranchID
};
And just pass the whole object to the other function:
someOtherFunction(newCountyInfo);
Which can access the fields using plain old property accesses:
function someOtherFunction(foo) {
console.log(foo.name); // whatever was in newCountyname
}
No JSON whatsoever.
Something like this should work just fine:
var newCountyInfo = {
name: newCountyName,
state: newCountyState,
zips: newCountyZips,
branchID: newCountyBranchID
}
function test(newCountyValidation)
{
alert(newCountyValidation.name);
}
test(newCountyInfo);

JavaScript JSON parse by a given key without looping

Given a JSON string as this:
{
"__ENTITIES": [
{
"__KEY": "196",
"__STAMP": 1,
"ID": 196,
"firstName": "a",
"middleName": "b",
"lastName": "c",
"ContactType": {},
"addressCollection": {
"__deferred": {
"uri": "/rest/Contact(196)/addressCollection?$expand=addressCollection"
}
},
"__ERROR": [
{
"message": "Cannot save related entity of attribute \"ContactType\" for the entity of datastore class \"Contact\"",
"componentSignature": "dbmg",
"errCode": 1537
}
]
}
]
}
Is there a method to get just the __ERROR record, I know I can use
var mydata = json.parse(mydata) and then find it from the mydata object. But I was hoping there was a method to only return the ERROR field something like
json.parse(mydata, "__ERROR") and that gets only the information in the __ERROR field without turning the whole JSON string into an object
"Is there a method to get just the __ERROR record, I know I can use var mydata = json.parse(mydata) ... But I was hoping there was ... something like json.parse(mydata, "__ERROR")"
There may be libraries that do this, but nothing built in. You need to write code that targets the data you want.
The closest you'll get will be to pass a reviver function to JSON.parse.
var errors = [];
var mydata = JSON.parse(mydata, function(key, val) {
if (key === "__ERROR")
errors.push(val);
return val
});
without turning the whole json string into an object
That's hardly possible, you would need some kind of lazy evaluation for that which is not suitable with JS. Also, you would need to write your own parser for that which would be reasonable slower than native JSON.parse.
Is there a method to get just the __ERROR record
Not that I know. Also, this is an unusual task to walk the whole object tree looking for the first property with that name. Better access __ENTITIES[0].__ERROR[0] explicitly.
If such a function existed, it would have to parse the whole thing anyway, to find the key you're looking for.
Just parse it first, then get the key you want:
var mydata = JSON.parse(mydata);
var errorObj = mydata.__ENTITIES[0].__ERROR[0];
If you want, you may create your own function:
function parseAndExtract(json, key) {
var parsed = JSON.parse(json);
return parsed[key];
}

Categories