In my page I have an applet. I'd like to pass a some data to an applet function. I've found out how to do this and it worked fine for simple datatypes like strings but I'm having hard time with some nested data structures. I'm not sure what would be the right term for it — a list of dictionaries or an array of associative arrays. Here's a snippet of my JavaScript data structure is built.
var servers = []
servers.push({'id' : 1, 'ip' : '111.111.111.111'});
servers.push({'id' : 2, 'ip' : '222.222.222.222'});
$('testapplet').setWork(servers);
How do I access this in Java? I'd like to iterate over them and print them to the console? I tried the following code but I couldn't get it to work.
public void setWork(HashMap s[]) {
for (int i = 0; i < s.length; i++) {
HashMap item = s[i];
System.out.println(item);
System.out.println(item.get("ip"));
}
}
I'm not sure the Java/JavaScript bridge support anything other than primitive types.
You could try serialising to JSON, then pass that over the bridge:
...yourcode....
$('testapplet').setWorker(toJSON(yourvar));
Edit: as just mentioned... :)
There maybe a better solution, but you could JSON stringify the data in Javascript and then decode it in Java.
Related
Is there a way to access a JSON value with a composed string key ?
Let me explain, I have a following JSON Object :
{
"guy1":
{
"name":"Joe"
}
}
Suppose we have an array guysArray containing multiple JSON Objects similar to the one above and a string variable
let pathToName = "guy1.name"
I noticed it's impossible to do like that :
guysArray[i].pathToName
The only correct way :
guysArray[i].guy1.name
guysArray[i]["guy1"]["name"]
How could I do that programmatically without having to write the path element by element ?
Am I obligated to create a loop structure or there is a better saving structure for pathToName ?
try this one :
let yourData = `{
"guy1":
{
"name":"Joe"
}
}`
let stringToJson = JSON.parse(yourData)
let wantedValue = stringToJson['guy1'].name
console.log(wantedValue)
How could I do that programmatically without having to write the path element by element ?
unfortunately there is not much more you can do with the bare operators and syntax of JavaScript without adding something like a custom function. You can do
> guysArray[i].guy1.name
"Joe"
but it's not gonna help you too much right now if you want something more general.
Am I obligated to create a loop structure or there is a better saving structure for pathToName?
A function would work fine, but you may find interesting the idea that the sequence of keys in a JSON could be the path to the value.
In your case the name is at the path "guy1.name" so you could do a function that takes in this path, splits it every "." and then walks the JSON using the elements of the path as the keys.
> fromPath(guysArray[i], "guy1.name")
"Joe"
This idea is described as JSONpath and should be doable for you to implement as your own function.
I know little about JS, still learning big time. However I am writing a NodeJS app that offers JSON web services to a Angular Frontend.
One problem I have is sometimes my objects have flat name/value pairs and sometimes my objects values will show up in Chromes Console as "address:Array[1]". While I can always do address[0] to get a value, there are parts of my code where I have both that and address: "12345" not sure how to handle it.
I would think it best to have all data output the same way but I cant seem to factor my node code to dump out flat name/value. Nor do I know how to create a Array[1] for a value.
This is the code that creates Array[1] values instead of flat name/value
json.nodes.node.forEach(function (rowData) {
dataObject.push({
name: rowData.name
,address: rowData.address
,enabled: rowData.enabled
})
})
This is the code that creates the flat name/value pairs
for (i = 60; i < 85; i++) {
dataObject.push({
name: i + "f"
,address: i
,enabled: true
})
Any help would be great! Thanks in advance!
I have a set of data in a JSON file that consists of UserIDs (as keys) and Passwords (values). I want to read the same using JavaScript for validation purposes. My JSON is :
IDsNPass = '[{"A":"A15"},{"B":"B15"},{"C":"C15"}]';
I have an idea about how to access the data using JavaScript as long as the keys in the JSON remain the same. But here, the keys in my JSON are not constant all along.
Any help on how to get along with the JavaScript is much appreciated!
First of all, your design is not a good format.
If you only have a id-password mapping in on object, you can do like this
var ip = JSON.parse(IDsNPass)
for(var obj in ip) {
for(var key in obj) {
console.info(key)
console.info(obj[key])
}
}
I am looking for a descriptive way to document the used data structures in my JavaScript application. I find it hard to get this done due to the dynamic character of JavaScript.
For instance, what could be a good way to tell, that a used variable distance is a two-dimensional array with length i and j and stores numbers between -1 and MAX_INT. I could think of something like this:
distance[i][j] = -1 <= n <= MAX_INT
What about an object which is used as a map/dictionary for certain data types, what about a two-dimensional array where the first element of an array defines other data then the rest, etc.
Of course, it is always possible to document these things in a text, I just thought, maybe there is a well known and used way to do this in a semiformal way.
Although it's not too widely adopted (yet?), there is a draft standard for JSON schema. I'm just learning it myself but you could write a schema for your two-dimensional array (wrapped inside of an object) as:
{
"description":"Two dimensional array of numbers",
"type":"object",
"properties":{
"two-d-array":{
"description":"columns",
"type":"array",
"items":{
"description":"rows",
"type":"array",
"items": {
"description":"values",
"type":"number",
"minimum":-1,
"maximum":Number.MAX_VALUE
}
}
}
}
}
or simply:
{
"type":"array",
"items":{
"type":"array",
"items": {
"type":"number",
"minimum":-1,
"maximum":Number.MAX_VALUE
}
}
}
There is no CoffeeScript implementation that I know of, but there is a list of several JavaScript validators here. I'm playing with the one that's written by the spec authors called (simply enough) json-schema and I like it well enough calling it from CoffeeScript.
What I tend to do in my JavaScript when I am replicating a lot of data models is to write out what their class definition would be in comments. I am not sure if this is what you meant with your question.
// JavaScript Class jsHomeLocation
// jsHomeLocation{
// string name
// string address
// }
var jsHomeLocation = {};
jsHomeLocation.name = "Travis";
jsHomeLocation.address = "California";
You could also use javascript objects to track the information of the example, a two-dimensional array
var distanceData = {};
distanceData.type = "two-dimensional array";
distanceData.length = i * j;
distanceData.min = -1;
distanceData.max = MAX_INT;
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/