I have a file containing of:
[{
'item1' : 'value1',
'item2' : [
'internalItem1' : 'value'
]
},
{
'item1' : 'value2',
'item2' : [
'internalItem1' : 'value',
'item2' : [
'internalItem1' : 'value',
'internalItem2' : 'value'
]
]
}]
I'd like to put it in an array of json objects. How can I do it? This is how I'm managing with a file containing of one JSON object:
$json = (Get-Content $fileLocation) | ConvertTo-Json
But the array of them is giving me nighthmares, how can I process this data?
Looks like you need commas on the end of the lines:
[{
'item1' : 'value1',
'item2' : {
'internalItem1' : 'value'
}
},
{
'item1' : 'value2',
'item2' : {
'internalItem1' : 'value',
'item2' : [{
'internalItem1' : 'value',
'internalItem2' : 'value'
}]
}
}]
Related
I have a 3 layer nested document something like this.
{
"_id" : ObjectId("5b5acaf0589ff6bfb5dd091f"),
"date" : "2018/07/31",
"clock" : [
{
"time" : "10:12:02",
"values" : [
{
"name" : "A1003",
"value" : "777"
},
{
"name" : "A0001",
"value" : "888"
}
]
},
{
"time" : "13:12:02",
"values" : [
{
"name" : "A1003",
"value" : "111"
}
]
}
]
}
I'm able to sort the date by using $gte $lte as below and all values are fetched.
getData(name: string[], fromDate: string, toDate: string): Promise<{ message: string }> {
return this._mongoUtility.testDb
.then(db => {
let collection = db.collection('TestDoc');
let fromOnlyDate = fromDate.split(' ');
let toOnlyDate = toDate.split(' ');
return collection.find({
'date': {
$gte: `${fromOnlyDate[0]}`,
$lte: `${toOnlyDate[1]}`
}
}).toArray();
})
.catch(err => {
return Promise.reject({message: 'Data not found', err: err})
})
}
I want to filter by using time and again by name and should display the value.
I tried in many ways but I'm getting the result. Is there nay other method to do so in MongoDB? Kindly suggest.
Expected output should look like below
0:{date: "2018/07/31 10:12:02", value-A1003: "777", value-A0001: "888"}
1:{date: "2018/07/31 13:12:02", value-A1003: "111"}
you can use the aggregate framwork to achive a simmler result(you cant create attr by value)
db.getCollection('sss').aggregate([
{$unwind:'$clock'},
{$unwind:'$clock.values'},
{$project:{
date: {$concat:[ "$date" ,' ' , "$clock.time" ]},
value:'$clock.values.value',
name:'$clock.values.name'
}}
])
Info: Using "yiisoft/yii2-elasticsearch": "2.1.x-dev"
I would like to do the following using yii2 elastic:
(from https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html)
{
"sort" : [
{
"_geo_distance" : {
"location" : {
"lat" : -33.936593,
"lon" : 18.4204544
},
"order" : "asc",
"unit" : "km"
}
}
],
"query": {
"bool" : {
"must" : {
"match_all" : {}
},
"filter" : {
"geo_distance" : {
"distance" : "3000km",
"location" : {
"lat" : -33.936593,
"lon" : 18.4204544
}
}
}
}
}
}
When I use the below:
$query = [
'bool' => [
// 'must' => [
// 'match_all' => [] // this throws a diff error
// ],
'filter' => [
'geo_distance' => [
'distance' => $distance . "km",
'location' => [
'lat' => $lat,
'lon' => $lng
]
]
]
]
];
$sort = [
'geo_distance' => [
'location' => [
'lat' => $lat,
'lon' => $lng
],
'order' => 'asc',
'unit' => 'km'
]
];
$models = Model::find()
->query($query)
->orderBy($sort)
->all();
I get error:
Exception 'yii\elasticsearch\Exception' with message 'Elasticsearch
request failed with code 400. Response body:
{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"[field_sort]
unknown field [location], parser not
found"}],"type":"illegal_argument_exception","reason":"[field_sort]
unknown field [location], parser not found"},"status":400}'
Maybe I can pass raw json query to yii2 elasticsearch? Not sure the yii2-elasticsearch lib is able to handle a 'location' (geo_distance) field yet ?
Help appreciated,
gvanto
you can use orderBy method and write something like this
MyModel::find()
->query(...)
->orderBy([
'post_date' => SORT_ASC,
'name' => SORT_DESC
])
->all()
I have a SwiftyJSON array that is nested several levels and I need to filter the array based on a value in the lowest level. Below is an example of an array. I need to filter it on Active == true. What is the most efficient way to accomplish this?
var colors = JSON([
"Apple" : [
"Yellow" : [
"Active" : true,
"Working" : true,
"Value" : 0
],
"Red" : [
"Active" : false,
"Working" : true,
"Value" : 0
]
],
"Banana" : [
"Blue" : [
"Active" : false,
"Working" : true,
"Value" : 0
],
"Green" : [
"Active" : true,
"Working" : true,
"Value" : 0
]
]
])
Desired output:
"Apple" : [
"Yellow" : [
"Active" : true,
"Working" : true,
"Value" : 0
]
],
"Banana" : [
"Green" : [
"Active" : true,
"Working" : true,
"Value" : 0
]
]
Check this out
var filteredArray = [JSON]()
for item in colors {
for subItem in item.1 {
if subItem.1["Active"].boolValue {
filteredArray.append(JSON([item.0:JSON([subItem.0:subItem.1])]))
}
}
}
print(filteredArray)
Output is the array of Dictionaries of filtered sub dictionaries with Active true:
[{
"Apple" : {
"Yellow" : {
"Working" : true,
"Value" : 0,
"Active" : true
}
}
}, {
"Banana" : {
"Green" : {
"Working" : true,
"Value" : 0,
"Active" : true
}
}
}]
you can create a loop that will read all colors and within this loop to create one that will read the other items in the second array. Within the second is you check if the item is valid or not and save it in another array
let activeItems = []
for item in colors {
for i in item as NSDictionary {
if i.objectForKey("Active") == true {
activeItems.addObject(i)
}
}
}
var result = [String:[String:JSON]]()
for (key, json) in colors.dictionaryValue {
let filtered = json.dictionaryValue.filter{$0.1["Active"].boolValue}
guard filtered.count > 0 else { continue }
var subDic = [String:JSON]()
filtered.forEach{subDic[$0.0] = $0.1}
result[key] = subDic
}
print(result)
I have this JSON string
[
{
uri : '/someuri/one',
title : 'Title 1',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-1'
},
{
uri : '/someuri/two',
title : 'Title 2',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-2'
},
{
uri : '/someuri/three',
title : 'Title 3',
displayLocation : 'ACTION_MENU',
masterData : 'JOB',
iconClass : 'icon-class-3'
},
{
uri : '/someuri/four',
title : 'Title 4',
displayLocation : 'SUMMARY',
masterData : 'LOCATION',
iconClass : 'icon-class-4'
}
]
I am converting it to
[
{
iconClass : 'icon-class-1',
id : 'anythingUnique',
text : 'Title 1'
},
{
iconClass : 'icon-class-2',
id : 'anythingUnique',
text : 'Title 2'
}
]
using following code
function myCustomFilter(inputJSONStr) {
return _.each(inputJSONStr.filter(function(action){
return action.masterData === 'LOCATION' && action.displayLocation === 'ACTION_MENU';
}), function (action) {
return [{iconClass: action.iconClass, id: 'anythingUnique', text: action.title}];
});
But its returning me JSON string
[
{
uri : '/someuri/one',
title : 'Title 1',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-1'
},
{
uri : '/someuri/two',
title : 'Title 2',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-2'
}
]
Can anyone suggest what I am doing wrong?
You could use map to do this:
_(inputJSONStr).filter({masterData: 'LOCATION', displayLocation: 'ACTION_MENU'})
.map(function(a) {
return {iconClass: a.iconClass, id: 'anythingUnique', text: a.title};
}).value();
I've changed your filter a little, but you could do it your way if you wanted, and I've used a functional approach with chaining, but you could do it imperatively if that makes you more comfortable. Map effectively replaces an array element with the returned element.
a simple table contains - id, name, text.
I need to bring these data in the grid with the grouping by the field name.
In all the examples that I found (for example - paper) uses the variable already defined the data. And I need to get data from Store.
ExtJs 3
The code:
Ext.onReady(function() {
var store = new Ext.data.JsonStore({
url : 'get_from_db.php',
storeId : 'MyStore',
totalProperty : 'totalCount',
idProperty : 'id',
remoteSort : true,
fields : [
{name : 'id', type : 'int'},
{name : 'name', type : 'String'},
{name : 'text', type : 'String'}
]
});
store.load();
var TestReader = new Ext.data.JsonReader({
idProperty : 'id',
fields : [
{name : 'id', type : 'int'},
{name : 'name', type : 'String'},
{name : 'text', type : 'String'}
]
});
var TestStore = new Ext.data.GroupingStore({
reader : TestReader,
data : 'get_from_db.php',
sortInfo : {
field : 'id',
direction : 'ASC'
},
groupField : 'name'
});
var TaskGrid = new Ext.grid.GridPanel({
store : TestStore,
columns : [
{id : 'id', header : 'Id', dataIndex : 'id'},
{id : 'name', header : 'Name', dataIndex : 'name'},
{id : 'text', header : 'Text', dataIndex : 'text'}
],
view : new Ext.grid.GroupingView({
forceFit : true,
groupTextTpl : '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
}),
frame : true,
width : 700,
height : 450,
collapsible : true,
animCollapse : false,
title : 'Grouping',
renderTo : document.body
});
});
As a result, output grid without a single error, the group is - but here's the column values - all zeros
post the code of 'get_from_db.php', if you can, please.
$connect = mysql_connect('localhost', 'root', ''); if ($connect) mysql_select_db('grid') or die('error with select table'); $select = mysql_query("select * from test"); while ($rec = mysql_fetch_array($select)) $rows[] = $rec; echo json_encode($rows);
You made mistake in returning JSON. Instead
$rows[] = $rec;
you need
$rows[] = array ("id"=>$rec['id'], "name"=>$rec['name'], "text"=>$rec['text']);
decided. code:
Ext.onReady(function() {
var TestStore = new Ext.data.GroupingStore({
url : 'http://extjs/get_from_db.php',
autoLoad : true,
remoteGroup : true,
groupField : 'name',
sortInfo : {
field : 'id',
direction : 'ASC'
},
reader : new Ext.data.JsonReader({
totalProperty : 'totalCount',
root : 'items',
idProperty : 'id',
fields: [
{name : 'id', type : 'int'},
{name : 'name', type : 'String'},
{name : 'text' ,type : 'String'}
]
})
});
var TaskGrid = new Ext.grid.GridPanel({
store : TestStore,
colModel : new Ext.grid.ColumnModel({
columns : [
{id : 'id', header : 'Id', dataIndex : 'id'},
{header : 'Name', dataIndex : 'name'},
{header : 'Text', dataIndex : 'text'}
],
defaults : {
sortable : true,
menuDisabled : false,
width : 20
}
}),
view : new Ext.grid.GroupingView({
startCollapsed : true,
forceFit : true,
groupTextTpl : '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
}),
frame : true,
width : 700,
height : 450,
collapsible : true,
animCollapse : false,
title : 'Grouping',
renderTo : document.body
});
});
More details in this note