I'm trying to filter my results by it's position.
But as soon a orderby it breaks the page since the result is not an array. How can I change this? I'm stuck with this.
I do this like so:
<div ng-repeat="cat in content | orderBy : 'pos'" class="animated zoomIn">
And the controller:
firebase.database().ref("v3/standalonelist/" + catId.toLowerCase()).on('value', function(snapshot) {
$timeout(function() {
$scope.content = snapshot.val();
console.log($scope.content);
})
});
$scope.content returns this object:
{
"Bar One" : {
"bgurl" : "https://domain.com/aa/bars/list/bar.jpg",
"name" : "Bar One",
"subtitle" : "Cheers",
"pos", 2
},
"Bar Two" : {
"bgurl" : "https://domain.com/aa/bars/list/bar.jpg",
"name" : "Bar Two",
"subtitle" : "Cheers",
"pos", 1
}
}
And i get this error:
[orderBy:notarray] Expected array but received: [THE OBJECT ABOVE]
1) Customized filter (AngularJS) for orderBy Object property..
Example JSON:
{
"123": {"name": "Test B", "position": "2"},
"456": {"name": "Test A", "position": "1"}
}
Try this link...
orderBy filter for Object
2) Another one way to acheive orderBy filter for Object properties.
Add an array of your data objects:
$scope.dataArray = Object.keys($scope.data)
.map(function(key) {
return $scope.data[key];
});
In view:
<div ng-repeat="item in dataArray | orderBy:'order.allListPosition'">
http://plnkr.co/edit/BXgYPTElSM3sjvLg30CL?p=preview
You model is object not an array, so you should use (key, value) in experssion synatx.
Related
I have the below json file which I want to split in NIFI
Input:
[ {
"id" : 123,
"ticket_id" : 345,
"events" : [ {
"id" : 3322,
"type" : "xyz"
}, {
"id" : 6675,
"type" : "abc",
"value" : "sample value",
"field_name" : "subject"
}, {
"id" : 9988,
"type" : "abc",
"value" : [ "text_file", "json_file" ],
"field_name" : "tags"
}]
}]
and my output should be 3 different jsons like below:
{
"id" : 123,
"ticket_id" : 345,
"events.id" :3322,
"events.type":xyz
}
{
"id" : 123,
"ticket_id" : 345,
"events.id" :6675,
"events.type":"abc",
"events.value": "sample value"
"events.field_name":"subject"
}
{
"id" : 123,
"ticket_id" : 345,
"events.id" :9988,
"events.type":"abc",
"events.value": "[ "text_file", "json_file" ]"
"events.field_name":"tags"
}
I want to know can we do it using splitjson? I mean can splitjson split the json based on the array of json objects present inside the json?
Please let me know if there is a way to achieve this.
If you want 3 different flow files, each containing one JSON object from the array, you should be able to do it with SplitJson using a JSONPath of $ and/or $.*
Using reduce function:
function split(json) {
return json.reduce((acc, item) => {
const events = item.events.map((evt) => {
const obj = {id: item.id, ticket_id: item.ticket_id};
for (const k in evt) {
obj[`events.${k}`] = evt[k];
}
return obj;
});
return [...acc, ...events];
}, []);
}
const input = [{"id":123,"ticket_id":345,"events":[{"id":3322,"type":"xyz"},{"id":6675,"type":"abc","value":"sample value","field_name":"subject"},{"id":9988,"type":"abc","value":["text_file","json_file"],"field_name":"tags"}]}];
const res = split(input);
console.log(res);
I have a JSON object as below and I need to pass some of the object via a jQuery Attribute tag. I am getting a JSON parse error but I am not sure why.
"Walkers" : "true",
"Owners" :[
{
"Name":"Bob",
"Description":"Old",
"Pets": [
{"Name" : "Cuddles", "Age": "8"},
{"Name" : "Pounce", "Age": "3"}
]
},
{
"Name":"Mary",
"Description":"Older",
"Pets": [
{"Name" : "Red", "Age": "13"},
{"Name" : "Leaf", "Age": "1"}
]
}
]
In my razor page I am serialising the section of the JSON object I need.
#foreach (var people in myjson) {
<p>#people.Walkers</p> //true
<div id="mytarget" data-owners='#Json.Serialize(people.Owners)'> </div>
}
In jQuery:
var val = $("#mytarget").data('owners');
console.log("json " + val); // result: json [object Object],[object Object]
console.log("parsed " + JSON.parse(val)); // result: VM7:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>)
If I don't use JSON.Parse and just try and loop through the object in JQuery I just end up with '0' and '1'
var val = $("#mytarget").data('owners');
for (var obj in val) {
Console.log(obj);
}
Result '0' and '1'.
I have a JSON object as below and I need to pass some of the object via a jQuery Attribute tag. I am getting a JSON parse error
If you use console.log(val); to output the val to console tab, you would find you have gotten a json array, like below.
when I try to use obj.Name I get 'undefined'
To extract data of owner and pets from that array, you can refer to the following code snippet.
var val = $("#mytarget").data('owners');
//console.log("json " + val);
console.log(val);
$.each(val, function (index, owner) {
//owner object
console.log("Name: "+owner.name+"; Description: "+owner.description);
//pets of current owner
$.each(owner.pets, function (index, pet) {
console.log("Name: "+pet.name+"; Age: "+pet.age);
})
})
That's because you're passing an array of object instead of an object
so in your console you're getting something like this:
[
{
"Name":"Bob",
"Description":"Old",
"Pets": [
{"Name" : "Cuddles", "Age": "8"},
{"Name" : "Pounce", "Age": "3"}
]
},
{
"Name":"Mary",
"Description":"Older",
"Pets": [
{"Name" : "Red", "Age": "13"},
{"Name" : "Leaf", "Age": "1"}
]
}
]
You can't parse an array like a object will be return a error.
You can also use devtools to see how the data is coming, maybe it is coming in another format, here is the docs for more info https://developers.google.com/web/tools/chrome-devtools/inspect-styles/
The error is in the for bucle the correct syntax is:
var val = $("#mytarget").data('owners');
for (i = 0; i < val.length; i++) {
console.log(val[i])
}
here is the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
Or you can use map: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/map
var val = $("#mytarget").data('owners');
val.map(item => {
console.log(item)
})
I'd like to select all elements with a certain match in the name of the property.
For example, all the properties whose name starts with 'pass' from this json:
{
"firstName": "John",
"lastName" : "doe",
"age" : 50,
"password" : "1234",
"phoneNumbers": [
{
"type" : "iPhone",
"number": "0123-4567-8888",
"password": "abcd"
},
{
"type" : "home",
"number": "0123-4567-8910",
"password": "fghi"
}
]
}
Would result something like this:
[
"1234",
"abcd",
"fghi"
]
I don't want filter by values, only by property names. Is it possible using jsonpath?
I'm using the method SelectTokens(string path) of Newtonsoft.Json.Linq
No, JSONPath defines expressions to traverse through a JSON document to reach to a subset of the JSON. It cannot be used when you don't know the exact property names.
In your case you need property values whose name starts with a specific keyword. For that, you need to traverse the whole JSON text and look for the property names which start with pass having a string type
var passwordList = new List<string>();
using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
while (reader.Read())
{
if(reader.TokenType.ToString().Equals("PropertyName")
&& reader.ValueType.ToString().Equals("System.String")
&& reader.Value.ToString().StartsWith("pass"))
{
reader.Read();
passwordList.Add(reader.Value.ToString());
}
}
passwordList.ForEach(i => Console.Write("{0}\n", i));
}
I am trying to parse a Json file in Qt application but i am stuck at a point.
I have a json file which contains arrays with properties. Now i have a Category class which has a items as member variable. Now i would like to parse the properties and create a unique category object and under this object i would like to add the properties.
I have achieved this by hardcoding:
auto vehicle = std::make_unique<Item>("Coordinates");
vehicle->addEntry(std::make_unique<PropertyItem>("TODO", "x", PropertyType::FLOAT, false, *vehicle.get()));
categories.emplace_back(std::move(vehicle));
void Model::loadItemsFromJson() {
// Vehicle
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json");
QJsonArray properties = obj["properties"].toArray();
/// No idea here how to achive
}
Should i change the Json for better handling or could this be achieved easily?
Thank you
--------------------------EDIT---------------------
Now my json looks like this:
{
"General": [{
"Address": "TODO",
"Readonly": false
},
],
"Coordinates": [{
"Address": "TODO",
"Readonly": false
}
]
]
}
and my implementation:
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json");
QVariantMap map = obj.toVariantMap();
for (auto& m : map.keys()) {
// How to create objects??
}
If you structure your JSON like your objects, e.g.
{
"Categories" : {
"General" : [{
"Address" : "TODO",
"Name" : "Name",
"Type" : "string",
"ReadOnly" : "true"
}, ...],
"World Coordinates" : [...]
}
Then you just parse out each CategoryItem and ScenarioPropertyItem
PropertyType toPropertyType(QJsonValue value); // forward declare
void ScenarioPropertiesModel::loadItemsFromJson() {
// Vehicle
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json")["Categories"].toObject();
for (auto & cat : obj)
{
auto category = std::make_unique<CategoryItem>(cat.name());
for (auto & prop : cat.value().toArray())
{
auto address = prop["Address"].toString();
auto name = prop["Name"].toString();
auto type = toPropertyType(prop["Type"]);
auto readonly = prop["Readonly"].toBool();
category->addEntry(std::make_unique<ScenarioPropertyItem>(address, name, type, readonly));
}
categories.emplace_back(std::move(category));
}
}
PropertyType toPropertyType(QJsonValue value)
{
static std::map<QString, PropertyType> propertyTypes =
{
{ "float", PropertyType::FLOAT },
{ "string", PropertyType::String },
// etc
}
return propertyTypes[value.toString()];
}
The structure of the json response I have to work with is giving me all sorts of trouble.
I would like to filter children elements based on the entityType field.
For example I want only element of Folder type.
JSON:
{
"id" : "df1d2550-1442-41b8-9588-785e229c5728",
"path" : "",
"name" : "",
"entityType" : "Folder",
"children" : {
"child1" : {
"id" : "02427ae5-364e-47d0-8998-0876c596d586",
"name" : "child1",
"entityType" : "Book"
},
"child2" : {
"id" : "2bcef8b3-d3a3-410e-a481-a69ec7dce24d",
"name" : "child2",
"entityType" : "Letter"
},
"child3" : {
"id" : "12ee8334-d596-4b59-a09d-c286117f3966",
"name" : "child2",
"entityType" : "Book"
},
"Art" : {
"id" : "e3f2980e-433c-4eaa-b444-ed9702949ffc",
"name" : "Art",
"entityType" : "Folder"
},
"English" : {
"id" : "8fe0f14a-6f76-41aa-9ab3-3e63cd5a900b",
"name" : "English",
"entityType" : "Folder"
}
},
"properties" : { },
"ancestors" : [ ]
};
The JS code:
$scope.isFolder = function(item) {
return item.entityType === "Folder";
};
HTML
<div ng-repeat="item in library.children | filter:isFolder">
<pre>{{item.name}} - {{item.entityType}}</pre>
</div>
This code will display all the children when I only want 2.
Any idea what I am doing wrong ?
Plunker
Thanks
The reason your filter doesn't work is that Filter works on arrays but you have an object literal.
So you can either convert your object literal into an array like:
{
"id" : "df1d2550-1442-41b8-9588-785e229c5728",
"path" : "",
"name" : "",
"entityType" : "Folder",
"children" : [
{
"id" : "02427ae5-364e-47d0-8998-0876c596d586",
"name" : "child1",
"entityType" : "Book"
},
{
"id" : "2bcef8b3-d3a3-410e-a481-a69ec7dce24d",
"name" : "child2",
"entityType" : "Letter"
},
{
"id" : "12ee8334-d596-4b59-a09d-c286117f3966",
"name" : "child2",
"entityType" : "Book"
},
{
"id" : "e3f2980e-433c-4eaa-b444-ed9702949ffc",
"name" : "Art",
"entityType" : "Folder"
},
{
"id" : "8fe0f14a-6f76-41aa-9ab3-3e63cd5a900b",
"name" : "English",
"entityType" : "Folder"
}
],
"properties" : { },
"ancestors" : [ ]
};
You can use below code to convert children's properties to an array:
var arr = [];
for (var key in library.children) {
if (obj.hasOwnProperty(key)) {
obj[key]["key"] = key
arr.push(obj[key]);
}
};
library.children = arr;
Or create your own filter than takes in the object literal as callum linington do.
I went through the documentation. Although it is not as explicit as you would expect, looks like the filter function will only work on Array elements and not objects.
In your example, library.children is an object, not an array. Hence, the filter function is never called (which you can check by adding a console statement inside the function).
The specific part in the documentation which mentions that the filter function is called on Array can be found here. You will find it in the "Argument" section, "expression" row - look for the function description. It says that the function is called on Arrays and not Objects, which is your scenario.
So you can easily solve this by writing your own filter here is your adapted plnkr
Simple filter:
app.filter('byKey', function () {
return function (array, key, value) {
var take = [];
angular.forEach(array, function (e) {
if (e[key] === value){
take.push(e);
}
});
return take;
}
});
Simple usage:
<div ng-repeat="item in library.children | byKey: 'entityType' : 'Folder'">
<pre>{{item.name}} - {{item.entityType}}</pre>
</div>
The breakdown:
return function (input, arg1.....argn) {
}
The above return function in the filter is what drives the filter, the input is what you specify on the left side of the | (pipe), in your case: item in library.children.
It's the right side that confuses people. The first string should be the filter name, in my case byKey as that is what I have named it. Each time you use : you are allowing yourself to pass an arg.
So, I have specified this:
return function (array, key, value) {}
The first argument - array, is specified by the left of the |. The remaining args are specified each time you use :, in your case
byKey : 'entityType' : 'Folder'
byKey = filter, 'entityType' = key, 'Folder' = the value of the key