Decomposing data from a json withangularjs - json

I have a json file that is requested from a server so i can't modify how is sent, but all the data i need is there, so i want to put that data into the charts, the thing is how i can break down the json file, because the relevant data is nested, the structure is
estados(array of object)
id (property)
name (property)
localidades (array of object)
id (property)
name (property)
type1 (object)
type2 (object) etc..
i need to retrieve the id data from the object estados and localidades then especific data one of the objects nested in localidades.
How i can do that? i only know how to go through every nested object by iteration, but decomposing it?
here is a json sample :
http://www.jsoneditoronline.org/?id=9cd4c3af94f14b1cca2d35226794ea78

The Lodash library (Or Underscore, if you prefer) is what you are looking for. You can use it to manipulate your collections any way you want (pretty much). You could potentially do without helper libraries, but it is much easier (and sometimes faster, though browser dependent [ref]) to do it this way.
Here are some examples in the jsFiddle I put together for a demo. Some example of how to access particular property of an object inside an array of objects:
$scope.findObjects = function () {
var estado = _.find($scope.allJson, {
"idEstado": $scope.idToSearch
});
$scope.exampleOutput = _.filter(estado.localidades, function (item) {
return item.demanda && (item.demanda.ata > 5);
});
};

Related

How can I use a json file if all elements are in one array?

I'm trying to learn to import JSON files into p5.js.
I'm using this list of English words: https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json
I already know how to import things when the entries are organized into respective categories. It seems every entry is in the same array, though. How can I import individual entries?
In this particular case the data you're loading isn't a regular array ([]) with values accessed using an integer index, but a JavaScript Object or associative array({}) with values accessed using a string instead of an integer index.
This is a key-value pair association.
Let's say you have a simple association:
let data = {
"firstName": "Nicholas",
"lastName": "Keough",
}
In the example above firstName and lastName are keys and "Nicholas" and "Keough" are values.
You can use array like [] and instead of an integer index, you'd use the key:
console.log(data["firstName"]);// prints "Nicholas"
console.log(data["lastName"]);// prints "Keough"
alternatively you can use dot notation:
console.log(data.firstName);// prints "Nicholas"
console.log(data.lastName);// prints "Keough"
In your case, let's say dictionary is a variable that holds the loaded JSON data,
you apply the same ideas above to access each word. For example:
console.log(data['absorbent']);//prints 1
or
console.log(data.absorbent.);//prints 1
If you need to loop over the values (and in your case, with the dictionary of 370101 values, you would really want to), you can use a for...in loop.
Alternatively, if you simply need to access the keys, not the values, as a single array you can use Object.keys()
Here's a basic example illustrating both options:
(Bare in mind the dictionary is large so it will take time to load and print the data to console)
let dictionary;
// preload JSON data
function preload(){
dictionary = loadJSON("https://raw.githubusercontent.com/dwyl/english-words/master/words_dictionary.json");
}
function setup(){
noLoop();
console.log('test');
// access JSON data with a for...in loop
for(let word in dictionary){
console.log("word: " + word + " value: " + dictionary[word]);
}
// optionally, access the associative array keys only as an array
console.log(Object.keys(dictionary));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

Get length/size of json data

I have use the following codes to get my json data with certain nodes.
console.log(Object.keys(data.Top["person"]).length);
It is work fine in following structure of json data array:
data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}}
However when the person only have one nodes, it always show the answer 2 to me, it should be answer 1.
data:{"Top":{"person":{"A":"a","B":"b"}}}
Is it possible to solve this error?
length property is supported by type array.
data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}} in case of this person is array enclosed with [ ]
Where as for data:{"Top":{"person":{"A":"a","B":"b"}}} person is just an object. Hence length is undefined for it.
If you are creating json out of string or formatting it make sure to include [ and ] for person attribute.
JSFiddle
https://jsfiddle.net/d6pqnckh/
Also use JSON formatter to test JSON structure.
UPDATE
Since you are not sure of JSON structure. What you could do is before accessing length of person check if it is an array or object.
if(Object.prototype.toString.call(data.Top.person) === '[object Array]')
alert(data.Top.person.length);
//It is an array
else
alert("I AM OBJECT"); //It is of an object type
Updated Fiddle: https://jsfiddle.net/wys7awuz/
To make it an array regardless https://jsfiddle.net/ofkboh6k/
var p = data.Top.person;
delete data.Top.person;
data.Top.person = [];
data.Top.person.push(p);
alert(data.Top.person.length);
Include this in else part of condition. It will make it an array.
length works for type array.
change your JSON to
data:{"Top":{"person":[{"A":"a","B":"b"}]}}

Manually parse json data according to kendo model

Any built-in ready-to-use solution in Kendo UI to parse JSON data according to schema.model?
Maybe something like kendo.parseData(json, model), which will return array of objects?
I was searching for something like that and couldn't find anything built-in. However, using Model.set apparently uses each field's parse logic, so I ended up writing this function which works pretty good:
function parse(model, json) {
// I initialize the model with the json data as a quick fix since
// setting the id field doesn't seem to work.
var parsed = new model(json);
var fields = Object.keys(model.fields);
for (var i=0; i<fields.length; i++) {
parsed.set(fields[i], json[fields[i]]);
}
return parsed;
}
Where model is the kendo.data.Model definition (or simply datasource.schema.model), and json is the raw object. Using or modifying it to accept and return arrays shouldn't be too hard, but for my use case I only needed a single object to be parsed at a time.
I actually saw your post the day you posted it but did not have the answer. I just needed to solve this problem myself as part of a refactoring. My solution is for DataSources, not for models directly.
kendo.data.DataSource.prototype.parse = function (data) {
return this.reader.data(data);
// Note that the original data will be modified. If that is not what you want, change to the following commented line
// return this.reader.data($.extend({}, data));
}
// ...
someGrid.dataSource.parse(myData);
If you want to do it directly with a model, you will need to look at the DataReader class in kendo.data.js and use a similar logic. Unfortunately, the DataReader takes a schema instead of a model and the part dealing with the model is not extracted in it's own method.

Cast JSON to Mongoose Schema to call Schema Method

I've looked at this question (Is there a native feature to convert string based JSON into Mongoose Schema object instance?) and it's related to my question but doesn't do exactly what I'm looking for.
Essentially, I have JSON I've fetched from an Express response and I'd like to cast it to a Mongoose object for the purposes of calling a schema method on the object.
My schema looks something like this:
var BlahSchema = new Schema({
folder: String,
filename: String,
original: String
});
...
// This is the function I wish to cal
BlahSchema.virtual('url').get(function () {
...
});
From what I understand, when I have an object matching BlahSchema, I can call the method via a simple object.url.
I have two questions. First, the JSON I'm retrieving these objects from erases their schema, right? I'm retrieving these from the database via Blah.search(...function(err, blahs)). This all gets encoded into a JSON object which I return via callback(req, res, search_result) where search_result is an object created via search_result.blahs = blahs, etc. Is there any way to preserve this schema across calls? This would be the preferred method.
Second, if the above is not possible, how do I re-cast JSON to schema without using the save() function mentioned in the answer to the question I pose above? I don't want to re-add objects to the database; I just want to use a method defined for that schema.
EDIT: Express is pretty sick. All you have to do is blah(object).method_name, where blah = mongoose.model('blah')
I save a User (Schema) object to redis in plain JSON.
Get the userData (string) and parse it to JSON object:
var user = new User(JSON.parse(userData))
... and you have all the methods of your User schema.

Parse a large file of non-schematized json using Jackson?

I have a very large .json file on disk. I want to instantiate this as a Java object using the Jackson parser.
The file looks like this:
[ { "prop1": "some_value",
"prop2": "some_other_value",
"something_random": [
// ... arbitrary list of objects containing key/value
// pairs of differing amounts and types ...
]
},
// ... repated many times ...
{
}
]
Basically it's a big array of objects and each object has two string properties that identify it, then another inner array of objects where each object is a random collection of properties and values which are mostly strings and ints, but may contain arrays as well.
Due to this object layout, there isn't a set schema I can use to easily instantiate these objects. Using the org.json processor requires attempting to allocate a string for the entire file, which often fails due to its size. So I'd like to use the streaming parser, but I am completely unfamiliar with it.
What I want in the end is a Map where the String is the value of prop1 and SomeObject is something that holds the data for the whole object (top-level array entry). Perhaps just the JSON which can then be parsed later on when it is needed?
Anyway, ideas on how to go about writing the code for this are welcome.
Since you do not want to bind the whole thing as single object, you probably want to use readValues() method of ObjectReader. And if structure of individual values is kind of generic, you may want to bind them either as java.util.Maps or JsonNodes (Jackson's tree model). So you would do something like:
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader(Map.class); // or JsonNode.class
MappingIterator<Map> it = reader.readValues(new File("stuff.json"));
while (it.hasNextValue()) {
Map m = it.nextValue();
// do something; like determine real type to use and:
OtherType value = mapper.convertValue(OtherType.class);
}
to iterate over the whole thing.