Create an object dynamically from JSON - javascript

Can I create an object dynamically from JSON?
This is one of some in array:
values: [{
"$type": "Entrance, DataModel",
"EntranceDeviceData": {
"$type": "DeviceData, DataModel",
"Watchdog": 0,
"Inputs": {
"$type": "Int16[], mscorlib",
"$values": [0, 0]
},
"Outputs": {
"$type": "Int16[], mscorlib",
"$values": [0, 0]
},
"Faults": {
"$type": "Int16[], mscorlib",
"$values": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
"StandingCommand": 0
},
"Vehicle": null,
"NextStates": {
"$type": "System.Collections.Generic.List`1[[System.String, mscorlib]], mscorlib",
"$values": ["CarApproachingBarrier"]
},
"Repository": {
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"
},
"Direction": 0,
"Name": "Entrance",
"Position": "0,0,0,0",
}, {...another object...
}, {...another one...
}
]
This both JSON objects are different. Can I create an object (for every other JSON object) without knowing in advance it's properties? How can I do it?
(I heard something that it possible, but maybe I didn't understand well the person who said that).

What you gave as examples of JSON in your original code above is Javascript's way of defining literal objects. json1 and json2 already ARE javascript objects, no need to create them.
// original code from question
var json1 = {
"mysex": "female",
"yoursex": "male",
"location": {
"lat": "48",
"lng": "1"
},
"description": "descr2",
"owner": "zBYnfuu8DXEwMttwZ",
"nickname": "user",
"_id": "1"
};
As nnnnnn pointed out below JSON is most commonly used to refer to a STRING containing code formatted as above, that would be:
var json1_as_string = '{
"mysex": "female",
"yoursex": "male",
"location": {
"lat": "48",
"lng": "1"
},
"description": "descr2",
"owner": "zBYnfuu8DXEwMttwZ",
"nickname": "user",
"_id": "1"
}';
To get from such a String to an actual Javascript Object you would need to parse it:
var json1 = JSON.parse(json1_as_string);
the opposite direction (Javascript Object to String) is achieved by stringify:
var json1_as_string = JSON.stringify(json1);
see https://developer.mozilla.org/en-US/docs/Using_native_JSON
p.s.
It does seem strange that these two very different objects have the same "_id".

You've changed the question completely, and I'm trying to understand what you are asking.
This both JSON objects are different. Can I create an object (for
every other JSON object) without knowing in advance it's properties?
How can I do it?
Yes, in Javascript you can create objects without knowing their properties in advance. Javascript is not strongly typed, and it has no classes. So there's absolutely no problem
with having objects with different properties.

Related

How to get specific data from object array?

I'm a beginner and would like to know how I can get a specific object from an array
I have an Array that looks like this:
data {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
},
To get the data from above I would do something like this:
return this.data.orderid
But how can I go deeper and get the status in userinfo?
return this.data.orderid.userinfo.status
doesn't work... anyone have any ideas?
A few points:
data is not an array, is an Object (see the curly braces, arrays have squared brackets). To be really precise, your syntax is invalid, but I assume you wanted to type data = { ... }, as opposed to data { ... }
Your syntax is almost correct, the only mistake you are making is that userinfo is an array, and arrays have numeric indexes (I.e. array[0], array[1]). What you are looking for is this.data.orderid.userinfo[0].status
Use data.userinfo[0].status to get the value (in your case this.data.userinfo[0].status)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
console.log(data.userinfo[0].status);
User Info is an array, so you would need to access it using indexer like so:
return this.data.userinfo[0].status
MDN on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
You need to iterate over data.userinfo (it's an array)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
data.userinfo.forEach(function(element) {
console.log(element.status);
});

JSON list optimization

I want to create a JSON API that returns a list of objects. Each object has an id, a name and some other information. API is consumed using JavaScript.
The natural options for my JSON output seems to be:
"myList": [
{
"id": 1,
"name": "object1",
"details": {}
},
{
"id": 2,
"name": "object2",
"details": {}
},
{
"id": 3,
"name": "object3",
"details": {}
},
]
Now let's imagine that I use my API to get all the objects but want to first do something with id2 then something else with id1 and id3.
Then I may be interested to be able to directly get the object for a specific id:
"myList": {
"1": {
"name": "object1",
"details": {}
},
"2": {
"name": "object2",
"details": {}
},
"3": {
"name": "object3",
"details": {}
},
}
This second option may be less natural when somewhere else in the code I want to simply loop through all the elements.
Is there a good practice for these use cases when the API is used for both looping through all elements and sometime using specific elements only (without doing a dedicated call for each element)?
In your example you've changed the ID value from 1 to id1. This would make operating on the data a bit annoying, because you have to add and remove id all the time.
If you didn't do that, and you were relying on the sorted order of the object, you may be in for a surprise, depending on JS engine:
var source = JSON.stringify({z: "first", a: "second", 0: "third"});
var parsed = JSON.parse(source);
console.log(Object.keys(parsed));
// ["0", "z", "a"]
My experience is to work with arrays on the transport layer and index the data (i.e. convert array to map) when required.

elasticsearch autosuggest returning tricky JSON

I'm running a node.js server that sends queries to an elasticsearch instance. Here is an example of the JSON returned by the query:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 9290,
"max_score": 0,
"hits": []
},
"suggest": {
"postSuggest": [
{
"text": "a",
"offset": 0,
"length": 1,
"options": [
{
"text": "Academic Librarian",
"score": 2
},
{
"text": "Able Seamen",
"score": 1
},
{
"text": "Academic Dean",
"score": 1
},
{
"text": "Academic Deans-Registrar",
"score": 1
},
{
"text": "Accessory Designer",
"score": 1
}
]
}
]
}
}
I need to create an array containing each job title as a string. I've run into this weird behavior that I can't figure out. Whenever I try to pull values out of the JSON, I can't go below options or everything comes back as undefined.
For example:
arr.push(results.suggest.postSuggest) will push just what you'd expect: all the stuff inside postSuggest.
arr.push(results.suggest.postSuggest.options) will come up as undefined even though I can see it when I run it without .options. This is also true for anything below .options.
I think it may be because .options is some sort of built-in function that acts on variables, so instead of seeing options as JSON and is instead trying to run a function on results.suggest.postSuggest
arr.push(results.suggest.postSuggest.options)
postSuggest is an array of object.options inside postSuggest is also array of object. So first you need to get postSuggest by postSuggest[0] and then
postSuggest[0].options to get array of options
This below snippet can be usefule
var myObj = {..}
// used jquery just to demonstrate postSuggest is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
document.write("<pre>Score is "+ item.score + " Text</pre>")
})
Jsfiddle

Indexing array values in an object in an IndexedDB

For a Chrome app, wich stores data in IndexedDB, i have a object like this:
var simplifiedOrderObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"address": "Foostreet 12, 12345 Bar York",
"orderitems": [
{
"item": "brush",
"price": "2.00"
},
{
"item": "phone",
"price": "30.90"
}
],
"parcels": [
{
"service": "DHL",
"track": "12345"
},
{
"service": "UPS",
"track": "3254231514"
}
]
}
If i store the hole object in an objectStore, can i use an index for "track", which can be contained multiple times in each order object?
Or is it needed or possibly better/faster to split each object into multiple objectStores like know from relational DBs:
order
orderitem
parcel
The solution should also work in a fast way with 100.000 or more objects stored.
Answering my own question: I have made some tests now. It looks like it is not possible to do this with that object in only 1 objectStore.
An other example object which would work:
var myObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"shipping": {"method": "letter",
"company": "Deutsche Post AG" }
}
Creating an index will be done by:
objectStore.createIndex(objectIndexName, objectKeypath, optionalObjectParameters);
With setting objectKeypath it is possible to address a value in the main object like "name":
objectStore.createIndex("name", "name", {unique: false});
It would also be possible to address a value form a subobject of an object like "shipping.method":
objectStore.createIndex("shipping", "shipping.method", {unique: false});
BUT it is not possible to address values like the ones of "track", which are contained in objects, stored in an array. Even something like "parcels[0].track" to get the first value as index does not work.
Anyhow, it would be possible to index all simple elements of an array (but not objects).
So the following more simple structure would allow to create an index entry for each parcelnumber in the array "trackingNumbers":
var simplifiedOrderObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"address": "Foostreet 12, 12345 Bar York",
"orderitems": [
{
"item": "brush",
"price": "2.00"
},
{
"item": "phone",
"price": "30.90"
}
],
"trackingNumbers": ["12345", "3254231514"]
}
when creating the index with multiEntry set to true:
objectStore.createIndex("tracking", "trackingNumbers", {unique: false, multiEntry: true});
Anyhow, the missing of the possibility to index object values in arrays, makes using indexedDB really unneeded complicated. It's a failure in design. This forces the developer to do things like in relational DBs, while lacking all the possibilities of SQL. Really bad :(

Parsing JSON with jQuery, retrieving two variables.

I have a online JSON file that looks something like this:
[
{
"j": 0,
"i": 0,
"DepartureTime": "\/Date(1331667480000+0100)\/",
"ArrivalTime": "\/Date(1331668860000+0100)\/",
"Remarks": [],
"TravelStages": [
{
"ID": 0,
"DepartureStop": {
"WalkingDistance": 0,
"ArrivalTime": null,
"AlightingAllowed": false,
"DepartureTime": null,
"BoardingAllowed": false,
"RealTimeStop": true,
"Rank": 0,
"Lines": null,
"StopPoints": [
{
"ID": 1,
"Name": "1",
"X": 608127,
"Y": 6645778
}
],
"Zone": "1",
"X": 608133,
"Y": 6645768,
"ID": 2300500,
"Name": "Visperud (i Solheimvn)",
"District": "Lørenskog",
"Type": 0,
"Stops": [],
"ShortName": "VIS"
}]
What I want is the grab out the DepartureTime and ArrivalTime, I've seen some examples on how to parse the flickr JSON. But I can't figure out how I can parse this. I also want to store the departureTime and arrivalTime in two separate variables since the content of this two is a time measured in milliseconds since 1970. Can somebody give me a hint on how a can do this, am totally new to Javascript/JSON
Do you have jQuery in your project? If so, you can easily parse the JSON string like this
var obj = $.parseJSON(theJsonText);
alert(obj.DepartureTime);
If not, I suggest including the JSON library (link) and using that.
You can try something like this, assuming that your json file is in jsonfile.json
$.getJSON('jsonfile.json', function(data){
alert("Departure Time: "+ data.DepartureTime);
alert("Arrival Time: "+ data.ArrivalTime);
});
http://api.jquery.com/jQuery.getJSON/
$.getJSON('http://your.domain.example/path/to/file.json', function(data) {
departure_time=data.DepartureTime;
arrival_time=data.ArrivalTime;
do_something_with(departure_time,arrival_time);
});
then do_something_with(str,str) would be called with the strings "\/Date(1331667480000+0100)\/" and "\/Date(1331668860000+0100)\/" (in your example).
you'll still have to convert the dates to numbers, e.g. by running:
parsed_date=new Date(parseInt(input_string.substr(7)));
//substr(7) cuts after "\/Date(", and parseInt ignores ")\/"
//but I don't know how it handles "+0100"
Thats an array containing objects, so you should be able to just set some vars equal to the properties of the first index. to use it like an object, it needs to be parsed.. so either eval(thatJson) or $.parseJSON(thatJson) and then iterate through it.
var responses = [
{
"j": 0,
"i": 0,
"DepartureTime": "\/Date(1331667480000+0100)\/",
"ArrivalTime": "\/Date(1331668860000+0100)\/",
"Remarks": [],
...
}];
var dep = responses[0].DepartureTime;
var arr = responses[0].ArrivalTime;
According to JSONLint.com, your string isn't valid JSON. That is, however, a different issue than what your question asks for.
Assuming a valid subset of your string
var a = '[{"j": 0,"i": 0,"DepartureTime": "/Date(1331667480000+0100)/", "ArrivalTime": "/Date(1331668860000+0100)/","Remarks": []}]';
var obj = $.parseJSON(a);
console.log(obj[0].ArrivalTime);​

Categories

Resources