Add items to JSON objects - javascript

I have a situation that I just cannot figure out how to do. I'm trying to add items to a JSON object that was sent from the controller.
Here's my models:
public class Model1
{
public Model2 item {get;set;}
public List<Model2> items {get;set;}
//
And in the page
var jsonData = #Html.Raw(JSON.Encode(Model))
This gives me the basic but empty model. Now in the page I fill in various fields and want to add the items into the model for posting. So:
jsonData.item.field1 = $("#field1").val();
Then I want to add to the list of items, but I cannot find anything that works:
jsonData.items.add(jsonData.item)
doesn't work throws an error.
jsonData.items.push(jsonData.item);
works but every item I add ends up the same. Meaning that when I add the second item there are two in the list but they have the same values. Any help would be appreciated.

As we know, Javascript can be used as OO language and classes and objects can be created on the fly in javascript.
Per my understanding, you are using below code to get class attributes in the JavaScript
var jsonData = #Html.Raw(JSON.Encode(Model))
When this JSON is returned to the client side, it is considered as single object.
So, you can declare a function, acting as class:
function Model2(jsonData ) {
this.name = jsonData.name;
this.discovered = jsonData.discovered;
};
var objModel2_1= new Model2(jsonData);
Now,
you can declare an array to add the objModel2.
var arrModel2=[];
// add new objects
attModel.push(objModel2_1);
Finally,
when you are done, you can use existing jsonData object to fill
i.e.
jsonData.item=objModel2_1;
jsonData.items=attModel;
Hope, this will help you.

Related

LINQ to select new object and has ICollection to return as Json

I checked similar questions such as:
How do I select a collection within a collection using LINQ?
How to return ICollection<object> from linq, when using select new object() {}
What I'm trying to do is return the list in Json format to be used in a Javascript GET request and display it on a cshtml page.
var query = (from c in db.photos
orderby c.date_created descending
select new { id = c.id, name = c.name, image_url = c.image_url, description = c.description, photos_has_characters = c.photos_has_characters.FirstOrDefault() })
.Skip(pageIndex * pageSize)
.Take(pageSize);
return Json(query.ToList(), JsonRequestBehavior.AllowGet);
However, when I go to the page nothing loads or shows an error I can pinpoint, so it has to be the photos_has_characters part in the LINQ.
How do I accomplish displaying those associated entities?
Let me re-clarify.
So I have a character's table and a photos tables with a many to many relationship table called photos_has_characters. I want to also select the character name and id from that photos_has_characters collection and return that information with the select new object. How do I do that?
If I'm missing something I will add it, thank you in advance.
EDIT:
In client-side on console I get this error:
What the LINQ is returning for photos_has_characters parameter...
Although it doesn't return an error, the parameter for new object of the photos_has_characters collection returns this:
photos_has_characters =
{System.Data.Entity.DynamicProxies.photos_has_character_A0E9952F88D75712B3DACC51D4EA09329C0427E5A9FED3F11F4EE0EC2AE1B579}
That into Json to be read using Javascript results in nothing. How do I modify my LINQ to accomodate?

How to add new key/value pair element to an existing array?

var onHomePageLoaded = function(retMsg)
{
$scope.data = retMsg.data.records;
$scope.data.link : 'http://www.newwebsite.com'
}
After i have added link element (key/value) to the javascript object, i am not able to get the same in the HTML template
<div ng-repeat="record in data">
<a ng-href="{{record.link}}"> Click Here </a>
</div>
Javascript is a dynamic language. You can add properties to existing objects in a very simple way , like assigning a value to an existing property. Just add a new property
$scope.data.link = 'http://www.newwebsite.com'
if retMsg.data.records is an array, still you can add a property to $scope.data.
if you want different link for every object in array then, do this.
$scope.data.forEach(function(obj){
obj.link = "your custom link" // write your logic here to produce different link.
});
If data is an array you can use
$scope.data.push(yourData);
for example
$scope.data.push({link : 'http://www.newwebsite.com'});
Or if you want to access the objects inside the array and add them a key value pair you can do as follow:
// add the link to the first entry
$scope.data[0].link = 'http://www.newwebsite.com';
Sorry. Do not know if I understood well.
Maybe you can define scope.data as:
$scope.data = {retMsg.data.records}
Then for example a function:
$scope.addNew = funtion(){
$scope.data.newElement = $scope.viewElement
};
In your HTML
<label>{{data}}</label> // Which makes reference to the $scope.data at the controller
<input ng-change="addNew()" ng-model="viewElement"></input>
<label>{{data.newElement}} // Will be empty at the very beginning but will show the new element once it is created.
Hope it helps
I see several issues with your code.
First, you use the variable name record in your ng-repeat, but then use report in ng-href. I assume those should be the same.
Also, link isn't a member of record, it is a member of data. You set it as a member of data here: $scope.data.link : 'http://www.newwebsite.com'. If you want to add that link to each record, in your onHomePageLoaded function, you'll need to loop through all the records you add to data, and add the link property to each one.

JSONSerializer to render a Java String Array

I have a Java array containing 5 strings. I want to plot this data using Flot Charts and thus I want to transfer it using render(array) from a Java file to an html file that will need Javascript. I have tried many things, and some users suggested me to just pass it to JSON in the Java file and then render it to make it easy to "digest" to Javascript.
One of the methods I've used is the following one:
JSONSerializer TestSerializer = new JSONSerializer();
String test = TestSerializer.serialize(array);
render(test);
I've tried to store it in a String test[] element (as an array), but it recognises the result to the serialization as a unique variable... However, the result I obtain when later on I assign into a variable ${test} in the html file to which I've done the render is the following one:
["Hello","Bye","Hi"]
With the strings "Hello", "Bye" and "Hi" placed like that, which is absolute garbage and is not useful to treat it with Javascript. Furthermore, if instead of render(array) I type renderJSON(array), all the html page goes blank but the array shows PERFECTLY as I want it, but obviously it is the only thing displayed in the content.
Do any of you have any idea of how to "transform" it or what could I do to get the desired ["Hello", "Bye", "Hi"] array in Javascript? Thanks!
Your question is not very clear.
So if I understood you right, you want something like a key:value relation.
Yes, you can do it with JSON and I also recommend you to use JSON.
The easy way is to use some library to do the parsing (Java->JSON) for you. I recommend you Gson.
An easy example with Gson, let's say you have a List of 4 objects type Person.
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then, you add each person to a List
Person john = new Person("John");
Person mark = new Person("Mark");
Person maria = new Person("Maria");
Person beth = new Person("Beth");
List<Person> personList = new ArrayList<>();
personList.add(john);
personList.add(mark);
personList.add(maria);
personList.add(beth);
Now comes the parsing, let's use Gson.
Gson gson = new Gson();
String jsonString = gson.toJson(personList);
At this point you already have the String with the JSON code in it. As I'm not sure if you just want the JSON String or the actual JSON Object, in case you want the JSON Object you can do the following:
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonString).getAsJsonArray();
They both hold the same information, but one in a String and the other in a JSON Object.
To make sure, you can do:
System.out.println("String: " + jsonString);
System.out.println("JSONArray.toString(): " + jsonArray.toString());
Which will print:
String: [{"name":"John"},{"name":"Mark"},{"name":"Maria"},{"name":"Beth"}]
JSONArray.toString(): [{"name":"John"},{"name":"Mark"},{"name":"Maria"},{"name":"Beth"}]
PS; If you want to change the key to something else you just need to change it on the Person class. Lets say you don't want you key to be as "name" but "firstName". You just go to the Person class and change the variable name to firstName
PS2; Using a parsing library for such a small example may look like an overkill but when your JSON object gets a little bit more complex it is a time saver.

Can I convert a json input to a list of objects within jquery?

I'm new to jQuery and just playing for fun. I have some code that I want to try to modify for my needs but the current js file is getting its data from google spreadsheets and then returning each item as objects. I don't use json to pass data from my server to jQuery so I'm wondering how I can convert json to objects.
The current way its doing it is(tabletop is the name of their js program that gets data from google docs):
Tabletop.init({
key: timelineConfig.key,
callback: setupTimeline,
wanted: [timelineConfig.sheetName],
postProcess: function(el){
//alert(el['photourl']);
el['timestamp'] = Date.parse(el['date']);
el['display_date'] = el['displaydate'];
el['read_more_url'] = el['readmoreurl'];
el['photo_url'] = el['photourl'];
}
});
I have added alerts all over the file and I think this is the area that gets the data and passes it on. I was thinking of trying to replace items in their object with objects from my json and see if it changes anything, but I'm unsure. Typrically I pass individual items via json,hashmaps, and lists, not sure how it works with objects or how to access objects(I simply call url's that I create for the requests, $("#user-history").load("/cooltimeline/{{ user.id }}");). But where do I start if I want to turn json data into objects?
If it helps, here's the demo of what I'm trying to do(but by having it use json data).
p.s. I'm really looking for the logic of how to complete what I'm trying to do and perhaps some ideas I'm missing so I can google them and learn.
Use use function JSON.parse(json) :) Or jQuery.parseJSON(json)
var json = '{"a":2}';
var object = JSON.parse(json);
alert(object.a);
You should see alert with message: 2
I don't realy know if I understand your comment, but maybe you want just do this:
postProcess: function(el){ //here el is JSON string
el = JSON.parse(el); // now el is an object
el.timestamp = Date.parse(el.date);
el.display_date = el.displaydate;
el.read_more_url = el.readmoreurl;
el.photo_url = el.photourl;
return el;
}
Btw. you do not need to use brackets on know property names without not standard names:
el['timestamp'] === el.timestamp
It will be easier if you paste your JSON

create json string on client side

I am trying to create the JSON string / object that is equivalent to the following data on the server side. can somebody help?
Public Shared Function GetData() As List(Of Employee)
Dim list As New List(Of Employee)()
Dim newEmployee As New Employee()
newEmployee.EmployeeID = "1"
newEmployee.FirstName = "Sridhar"
newEmployee.Title = "Programmer"
newEmployee.BirthDate = "8/10/1979"
newEmployee.TitleOfCourtesy = "Programmer"
list.Add(newEmployee)
Return list
End Function
Employee is a class with the properties EmployeeId, FirstName, Title, Birthdate, TitleOfCourtesy.
Thanks,
sridhar.
Keep in mind that in Javascript there is no concept of a class, only objects. This also carries over into JSON. Look at this:
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
}
}
If you look at the first line, the "Employee" symbol does absolutely nothing for the JSON. Remember that we're dealing with ONLY objects.
Thats why this works, like you said.
[
{"EmployeeID":1,
"LastName":"Duggireddy",
"FirstName":"Sridhar",
"Title":"Programmer",
"TitleOfCourtesy":"Programmer",
"BirthDate":new Date(303091200000)}
]
To make this programatically, declare your employee objects, and just add them into an array, like so:
var employees = [];
employees.push(employee1); // you would use a loop, of course
employees.push(employee2);
...
var jsonString = parser.toJSON(employees); // or whatever you use.
That should give you a list of objects. Always ignore the class in JSON... .NET during the deserialization will attempt to coerce the object into that particular class. You only have problems if this fails - maybe because a variable is missing or of the wrong type.
Why not just use JSON.NET and let it handle encoding/decoding for you?
It will look like
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
}
}
Reference
I believe multiple instances of Employee in the JSON would look like this:
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
},
{
"EmployeeID":"2",
"FirstName":"Joe",
etc...
}
}
Maybe that is what you need?
There's a good jQuery plugin for JSON. It lets you go from a JavaScript object to JSON very easily.
http://code.google.com/p/jquery-json/

Categories