I am new to SQL statements so my wording per my request may be incorrect, so I will provide a lot of detail to better understand my issue.
I have a database table called workouts that looks like this:
id
bodyPart
gifUrl
name
target
broad_target
1
back
http://d205bpvrqc9yn1.cloudfront.net/0007.gif
alternate lateral pulldown
lats
back
2
chest
http://d205bpvrqc9yn1.cloudfront.net/0009.gif
assisted chest dip (kneeling)
pectorals
chest
3
lower legs
http://d205bpvrqc9yn1.cloudfront.net/1708.gif
assisted lying calves stretch
calves
legs
4
upper legs
http://d205bpvrqc9yn1.cloudfront.net/1709.gif
assisted lying glutes stretch
glutes
legs
5
upper legs
http://d205bpvrqc9yn1.cloudfront.net/1710.gif
assisted lying gluteus and piriformis stretch
glutes
legs
6
back
http://d205bpvrqc9yn1.cloudfront.net/0015.gif
assisted parallel close grip pull-up
lats
back
and I want it to combine all the broad_muscles together and wrap it under an array called data.
Ideally, it would look like this:
{
title: 'Leg',
data:[
{
"bodyPart": "lower legs",
"equipment": "assisted",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1708.gif",
"id": "1708",
"name": "assisted lying calves stretch",
"target": "calves",
"broad_target": "legs",
"ppl": "legs"
},
{
"bodyPart": "lower legs",
"equipment": "smith machine",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1396.gif",
"id": "1396",
"name": "smith toe raise",
"target": "calves",
"broad_target": "legs",
"ppl": "legs"
}
]
}
I will return it via. Lambda in Node.JS, so if needed, the answer can be how to parse it in Node.JS.
Thanks!
You can something do like this, but if your o/p formats in an array. You should use any SQL orms that can be helpful.
const sampleData = [{
"id":"1",
"bodyPart":"back",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/0007.gif",
"name": "alternate lateral pulldown" ,
"target": "lats",
"broad_target" : "back"
},{
"id":"2",
"bodyPart":"chest",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/0007.gif",
"name": "assisted chest dip (kneeling)" ,
"target": "pectorals",
"broad_target" : "chest"
},{
"id":"2",
"bodyPart":"upper legs",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/0007.gif",
"name": "assisted chest dip (kneeling)" ,
"target": "glutes",
"broad_target" : "legs"
},{
"id":"2",
"bodyPart":"lower legs",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/0007.gif",
"name": "assisted chest dip (kneeling)" ,
"target": "calves",
"broad_target" : "legs"
}];
const matchString = "legs";
const output = sampleData.reduce((prev, current) => {
if (current?.broad_target === matchString) {
prev['title'] = "Leg";
prev['data'] = (prev['data'] || []);
prev['data'].push(current);
}
return prev
},{});
console.log(output);
Note: I have taken sample o/p as the sample the information might not match the actual data.
Related
I'm relatively new to Power Query, but I'm pulling in this basic structure of JSON from a web api
{
"report": "Cost History",
"dimensions": [
{
"time": [
{
"name": "2019-11",
"label": "2019-11",
…
},
{
"name": "2019-12",
"label": "2019-12",
…
},
{
"name": "2020-01",
"label": "2020-01",
…
},
…
]
},
{
"Category": [
{
"name": "category1",
"label": "Category 1",
…
},
{
"name": "category2",
"label": "Category 2",
…
},
…
]
}
],
"data": [
[
[
40419.6393798211
],
[
191.44
],
…
],
[
[
2299.652439184997
],
[
0.0
],
…
]
]
}
I actually have 112 categories and 13 "times". I figured out how to do multiple queries to turn the times into column headers and the categories into row labels (I think). But the data section is alluding me. Because each item is a list within a list I'm not sure how to expand it all out. Each object in the date array will have 112 numbers and there will be 13 objects. If that all makes sense.
So ultimately I want to make it look like
2019-11 2019-20 2020-01 ...
Category 1 40419 2299
Category 2 191 0
...
First time asking a question on here, so hopefully this all makes sense and is clear. Thanks in advance for any help!
i am also researching this exact thing and looking for a solution. In PQ, it displays nested arrays as a list and there is a function to extract values choosing a separating characterenter image description here
So this becomes, this
enter image description here
= Table.TransformColumns(#"Filtered Rows", {"aligned_to_ids", each Text.Combine(List.Transform(_, Text.From), ","), type text})
However the problem i'm trying to solve is when the nested json has multiple values like this: enter image description here
And when these LIST are extracted then an error message is caused, = Table.TransformColumns(#"Extracted Values1", {"collaborators", each Text.Combine(List.Transform(_, Text.From), ","), type text})
Expression.Error: We cannot convert a value of type Record to type Text.
Details:
Value=
id=15890
goal_id=323
role_id=15
Type=[Type]
It seems the multiple values are not handled and PQ does not recognise the underlying structure to enable the columns to be expanded.
I want to take all names from JSON delhi_hos file and store it in String, So that player can play That String. Right Now It plays one by one name. So Suggest Something Please.
JSON Example
[
{
"id": 1,
"name": "JW Marriott Hotel",
"country": "IN"
},
{
"id": 2,
"name": "Le Méridien Hotel",
"country": "IN"
},
{
"id": 3,
"name": "The Leela Palace Hotel",
"country": "IN"
}
]
My Code
if "Hospital".lower() in sentence.lower():
# print("Which City?")
# print("1.Surat \n 2.Pune \n 3.Delhi")
with open("store.txt", 'a') as store:
store.truncate(0)
if element['name'].lower() in sentence.lower():
for items in delhi_hos:
name3 = items.get('name')
print(name3)
my_text = "Near is " + name3
my_obj = gTTS(text=my_text, lang=language, slow=False)
my_obj.save("welcome.mp3")
os.system("mpg123.exe welcome.mp3")
with open("store.txt", "r+") as text_file:
text_file.truncate(0)
and I want Names From JSON file in string Like This
"JW Marriott Hotel Le Méridien Hotel The Leela Palace Hotel"
and the Store it in the variable.
var = "JW Marriott Hotel Le Méridien Hotel The Leela Palace Hotel"
So, I can use var as a input for my player to play this string.
My main Problem Is to convert all name into this string.
I don't know if I understand your question right. But as far as I understand, you simply want to have the values of the namefield in your JSON stringifyed.
I'm wondering why whats solution doesn't work as expected.
The simplest solution that comes to my mind would be:
names = ""
for item in delhi_hos:
names += item['name']
I suggest to start with small bites of a problem, when things don't work out. First add a print, when this works, assign variables, then add if statements and so on! Good Look!
I hope this solves your problem. Add proper indentation if any error comes.
import functools
obj = [
{
"id": 1,
"name": "JW Marriott Hotel",
"country": "IN"
},
{
"id": 2,
"name": "Le Méridien Hotel",
"country": "IN"
},
{
"id": 3,
"name": "The Leela Palace Hotel",
"country": "IN"
}
]
var = functools.reduce(lambda a, b : a + " " + b["name"], obj, "")
print(var)
I am new to Ember and JSON. I want to parse a JSON object that is below with typeahead library
and access nested object values by searching their keys.
I have this Json format:
return [
{
"id": 1,
"category_name": "Supermarket",
"category_description": "SUPER MARKET",
"image_url": "",
"merchants": [
{
"name": "CARREFOUR",
"id": 12,
"merchant_type_id": 1,
"merchant_type_description": "Gold",
"merchant_redeption_rate": 0.002500,
"image_url": "https://jpg",
"branches": [
{
"id": 123456,
"latitude": 37.939483,
"area": "ΑΓ. ΔΗΜΗΤΡΙΟΣ",
"zip": "12345"
},
{
"id": 4567890,
"longitude": 23.650622,
"area": "ΑΓ. ΙΩΑΝΝΗΣ ΡΕΝΤΗΣ",
"zip": "12345"
}
]
},
{
"name": "CAFCO",
"id": 13,
"merchant_type_id": 3,
"merchant_type_description": "None",
"merchant_redeption_rate": 0.002500,
"image_url": "https:.jpg",
"branches": [
{
"id": 127890,
"latitude": 38.027870,
"area": "ΠΕΡΙΣΤΕΡΙ",
"zip": "12345"
}
]
}
]
},
{
"id": 2,
"category_name": "Πολυκαταστήματα",
"category_description": "ΠΟΛΥΚΑΤΑΣΤΗΜΑ",
"image_url": "",
"merchants": [
{
"name": "AGGELOPOYLOS CHR.",
"id": 15,
"merchant_type_id": 2,
"merchant_type_description": "Silver",
"merchant_redeption_rate": 0.002500,
"image_url": "https://www.nbg.gr/greek/retail/cards/reward-programmes/gonational/PublishingImages/aggelopoulos.jpg",
"branches": [
{
"id": 234780,
"latitude": 35.366118,
"longitude": 24.479461,
"address": "ΕΘΝ. ΜΑΚΑΡΙΟΥ 9 & ΕΛ. ΒΕΝΙΖΕΛΟΥ 1",
"area": "Ν. ΦΑΛΗΡΟ",
"zip": "12345"
}
]
}
]
}
];
--------------------------Updated----------------------------
For example, i want to search using typeahead the name of merchants and when the letter we write to search matches the name of merchants it will appear the corresponding category_name and backwards.
Example -> when i keyboard the s it will appear :
Category : Supermarket,
Name: CARREFOUR
Name: CAFCO
And the same output on the dropdown of search when i keyboard the letter c.
Any help?
New Jsbin example
The simplest way (in my mind) to get this to work is to create a computed property that will contain an array of latitudes. But how do we get there?
To get to latitude, you need to go through array of merchants and then array of branches. Being that this will be across multiple elements, you are going to end up with "array of arrays" type data structure, which is annoying to deal with. So, to simplify this, we can create a simple flatten function as follows:
flatten: function(origArray){
var newArr = [];
origArray.forEach(function(el) {
el.forEach(function(eachEl){
newArr.push(eachEl);
});
});
return newArr;
},
In addition to our function above, Ember already provides us with many other useful functions that can be used on arrays (see here). One of those is mapBy(property) which transforms an array into another array only keeping the values of the property we specified.
So, to create a lats (for latitudes) property, we can just do this:
lats: function(){
var merchantsArr = this.get('model').mapBy('merchants');
merchantsArr = this.flatten(merchantsArr);
var branchesArr = merchantsArr.mapBy('branches');
branchesArr = this.flatten(branchesArr);
return branchesArr.mapBy("latitude").compact();
}.property('model')
Above, I am basically using mapBy, flatten (see above) and compact which
Returns a copy of the array with all null and undefined elements removed.
Once you have the lats property with all the necessary data, the rest is easy.
Your call to component becomes:
{{x-typeahead data=lats name='category_name' selection=myColor}}
Note lats instead of model you originally were passing into the component.
And now, to access the value of data property in the component, you do
`this.get('data')`
which you can just pass in as the source like so:
source: substringMatcher(self.get('data'))
Working solution here
Update
Updating my answer based on your updated question.
OK, so this is getting a little more complicated. You now need more than just one property (latitude) from the object. You need category_name and merchant name.
In addition to mapBy, which just grabs one property out of array, Ember also has map which lets you transform the array into pretty much anything you want to:
lats: function(){
var merchantsArr = this.get('model').map(function(thing){
var category_name = thing.category_name;
return thing.merchants.map(function(merchant){
return {
"name": merchant.name,
"category": category_name
};
});
});
merchantsArr = this.flatten(merchantsArr);
return merchantsArr;
}.property('model')
The code above looks complicated, but it's basically just returning an array of top level objects' merchants accompanied by category_name. Since this is an array of arrays, we will need to flatten it.
Then, inside the component, we need to keep in mind that we are not just passing in an array of strings, but rather we are passing in an array of objects. Therefore, we need to look through object's properties (name and category) for a match
$.each(strs, function(i, str) {
if (substrRegex.test(str.name) || substrRegex.test(str.category)) {
matches.push(str);
}
});
Lastly, to actually display both category and merchant name, you need to tell Typeahead how to do that:
templates: {
suggestion: Handlebars.compile('<p>{{name}} – {{category}}</p>')
}
Working solution here
I've been playing with the google feed API for a podcasts I run and wanted to include a simple ng-repeat to display the title and link URL to the MP3. However the JSON google provides is nested in several different Objects and Arrays. For instance, my JSON feed looks like this:
{
"responseData": {
"feed": {
"feedUrl": "http://feeds.feedburner.com/stillgotgame",
"title": "2old2play presents Still Got Game",
"link": "http://www.2old2play.com/",
"author": "",
"description": "Still Got Game focuses on the gaming industry from the perspective of adult gamers. We look at news, reviews, and inside information in the world of video games. Each episode touches on the community, the industry, and the games that keep us coming back.",
"type": "rss20",
"entries": [
{
"mediaGroups": [
{
"contents": [
{
"url": "http://traffic.libsyn.com/dsmooth/Still_Got_Game_Episode_33__Coast_to_Coast.mp3",
"fileSize": "35346436",
"type": "audio/mpeg"
}
]
}
],
"title": "Still Got Game Ep. 33: Coast to Coast",
"link": "http://2old2play.com/media/still-got-game-ep-33-coast-coast/",
"author": "podcast#2old2play.com",
"publishedDate": "Tue, 06 May 2014 22:05:01 -0700",
"contentSnippet": "DSmooth finally has his Rocket Bro back. After a multi-week hiatus for Doodirock's move to the West Coast, they boys were back ...",
"content": "DSmooth finally has his Rocket Bro back. After a multi-week hiatus for Doodirock's move to the West Coast, they boys were back in force this week. The duo talk gaming news and the new releases, cover a bunch of viewer feedback, and talk a bit about what may be the worst moving company ever. They'll have you LMFAOing! You can always call the boys at (773) 527-2961 and weigh in yourself, or tune in live Monday nights at 9:00 EDT at http://twitch.tv/2old2play ...",
"categories": [
"Audio"
]
}
]
}
},
"responseDetails": null,
"responseStatus": 200
}
As you can see, in order to get to the items URL to the MP3 I have to go through entries, mediaGroups, and Contents before I even reach the Array I need! I start off inside the entries with this factory I've created:
.factory('audioFEED', function($resource){
return $resource('http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=100&q=http://feeds.feedburner.com/stillgotgame',{},
{
query:{
method:'JSONP',
params: {callback: 'JSON_CALLBACK'},
isArray:false,
headers:{
'Access-Control-Allow-Origin': '*'
}
},
});
});
Thats easy enough with just setting up the data on the controller here:
'use strict';
angular.module('twitchappApp')
.controller('audioCtrl', function($scope, audioFEED) {
audioFEED.query(function(data){
$scope.audios = data.responseData.feed.entries;
console.log($scope.audios);
});
});
However, In order to get to that data I'm having to set up multiple ng-repeats with on inside of the next. I would really like to find a better way to handle this data within the controller and access the URL inside one ng-repeat. It seems this way is adding more over head and probably not the best over all method. Is there a best practice for this? My current end result looks like this:
<h1>Audio</h1>
<div ng-repeat="audio in audios">
<h3>{{ audio.title }}</h3>
<p>{{audio.contentSnippet}}</p>
<div ng-repeat="play in audio.mediaGroups">
<div ng-repeat="playurl in play.contents">
PLAY
</div>
</div>
</div>
Yuk...
Check out this JSFiddle. Uses underscore to flatten your data down to an easier to work with array. http://jsfiddle.net/ahchurch/sKeY9/3/
Template
<div ng-controller="MyCtrl">
<div ng-repeat="playurl in contents">
PLAY
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
var responseData = {
"responseData": {
"feed": {
"feedUrl": "http://feeds.feedburner.com/stillgotgame",
"title": "2old2play presents Still Got Game",
"link": "http://www.2old2play.com/",
"author": "",
"description": "Still Got Game focuses on the gaming industry from the perspective of adult gamers. We look at news, reviews, and inside information in the world of video games. Each episode touches on the community, the industry, and the games that keep us coming back.",
"type": "rss20",
"entries": [
{
"mediaGroups": [
{
"contents": [
{
"url": "http://traffic.libsyn.com/dsmooth/Still_Got_Game_Episode_33__Coast_to_Coast.mp3",
"fileSize": "35346436",
"type": "audio/mpeg"
}
]
}
],
"title": "Still Got Game Ep. 33: Coast to Coast",
"link": "http://2old2play.com/media/still-got-game-ep-33-coast-coast/",
"author": "podcast#2old2play.com",
"publishedDate": "Tue, 06 May 2014 22:05:01 -0700",
"contentSnippet": "DSmooth finally has his Rocket Bro back. After a multi-week hiatus for Doodirock's move to the West Coast, they boys were back ...",
"content": "DSmooth finally has his Rocket Bro back. After a multi-week hiatus for Doodirock's move to the West Coast, they boys were back in force this week. The duo talk gaming news and the new releases, cover a bunch of viewer feedback, and talk a bit about what may be the worst moving company ever. They'll have you LMFAOing! You can always call the boys at (773) 527-2961 and weigh in yourself, or tune in live Monday nights at 9:00 EDT at http://twitch.tv/2old2play ...",
"categories": [
"Audio"
]
}
]
}
},
"responseDetails": null,
"responseStatus": 200
};
//Underscore:
$scope.contents = _.flatten(_.map(responseData.responseData.feed.entries, function(entry){
return _.map(entry.mediaGroups, function(mediaGroup){
return mediaGroup.contents;
});
}));
$scope.name = 'Superhero';
}
I'm trying to get all champions of the Super Bowl.
I used the Query Editor and wrote this code:
[{
id: "/en/super_bowl"
"/sports/sports_championship_event/champion" : [{}]
}]
But everything I get is this:
{
"code": "/api/status/ok",
"result": [{
"/sports/sports_championship_event/champion": [],
"id": "/en/super_bowl"
}],
"status": "200 OK",
"transaction_id": "cache;cache02.p01.sjc1:8201;2013-01-21T20:27:29Z;0064"
}
Can anybody help me, please?
If you go to the topic page for /en/super_bowl you'll see that the Super Bowl is a Sports League Championship which is composed of individual Sports League Championship Events (eg. Super Bowl XLVI).
Your query is asking for all the champions of the Super Bowl when what you need to be querying for are the champions of each of the individual Super Bowl Championship Events in Freebase. That query looks like this:
{
"id": "/en/super_bowl",
"/sports/sports_championship/events": [{
"/sports/sports_championship_event/champion": [{}]
}]
}
You can adapt this query to get the winning team and the year like this:
{
"id": "/en/super_bowl",
"/sports/sports_championship/events": [{
"name": null,
"season": {
"/time/event/start_date": null
},
"/sports/sports_championship_event/champion": [{
"id": null,
"name": null
}]
}]
}
Go Niners!