How can I get the Path value in this Json? - powershell

I have a Json which is similar to this sample here
{
"vaults": {
"43371adf": {
"path": "C:\\Users\\user23\\Documents\\Mango Vault",
"ts": 16767
},
"54a80cfadc691ec4": {
"path": "C:\\Users\\user23\\Documents\\Apple Vault",
"ts": 166576
},
"af524734": {
"path": "C:\\Users\\user23\\Documents\\Orange Vault",
"ts": 166985
},
"40290aab5": {
"path": "C:\\Users\\user23\\Documents\\Banana Vault",
"ts": 167293,
"open": true
}
},
"frame": "hidden"
}
I am interested in retrieving the values for the keys Path. Some things I tried are:
$vaultsIndex = Get-Content -Path "C:\Temp\sample.json" | ConvertFrom-Json
$vaultsIndex.vaults
$vaultsIndex.vaults | foreach {$_.where -eq 'path'} #Returns 'False'
$vaultsIndex.vaults.where -eq 'path' #Also Returns 'False'
The only thing that works is $vaultsIndex.vaults.43371adf which I cant automate at all, I really need to just be all to get all the paths in a generic way.
The searches I performed just pointed me to this $_.where() method. Any help would be greatly appreciated!

You can access an object's Properties by calling .PSObject.Properties over said object. Since you're interested only in the path of each object in vault, we can call the .Value property of the property collection to access them and from there call .path over each object to get the values. This is done via member-access enumeration:
$json.vaults.PSObject.Properties.Value.path

Related

Firebase redirect example from the docs throws error: Unexpected token. Why?

I wanted to add redirects to my firebase project, so I pasted the example from the offical docs as a test:
"hosting": {
// ...
"redirects": [ {
"regex": "/blog/(?P<post>.+)", // if you're familiar with PCRE, be aware that RE2 requires named capture groups to begin with ?P
"destination": "https://blog.myapp.com/:post", // includes the entire URL segment identified and captured by the `regex` value
"type": 301
}, {
"regex": "/users/(\d+)/profile", // uses the \d directive to only match numerical path segments
"destination": "/users/:1/newProfile", // the first capture group to be seen in the `regex` value is named 1, and so on
"type": 301
} ]
}
When I tried to deploy I got the error:
Error: There was an error loading firebase.json:
Unexpected token 'd' at 28:26
"regex": "/users/(\d+)/profile",
^
How come the official example gets a syntax error? What is the problem?
You need to escape the backslash \\d.

is there a way to put web-activity result into sql-table (sink)

Unable to get the output of a web activity into a sql-table using azure-data-factory.
This is what i have done and where im getting stuck (Step 3).
Steps:
1.Get a token from a API-call
Get the results from API Call using token from step 1
and tkae this results in a successfull query that provides me with 'JSON'
Take the result from previous activity 'JSON' and put in in a azure sql database table.
azure-datafactory - web activites
Can you not get this done using a copy activity ? You should configure the source as Web activity and sink as SQL. I was playing with this http://dummy.restapiexample.com/api/v1/employees and we needed to introduce the structure . This is what I did and it work .
"source": {
"type": "RestSource",
"httpRequestTimeout": "00:01:40",
"requestInterval": "00.00:00:00.010",
"structure": [
{
"id": "id"
},
{
"employee_salary": "employee_salary"
}
]
},
"sink": {
"type": "SqlServerSink",
"writeBatchSize": 10000
},
"enableStaging": false
},
You can read more . https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-schema-and-type-mapping

Adding a key/value pair to an object in VTL (for API Gateway)

I am writing a mapping template for an AWS API Gateway integration response. I would like to add a key/value pair to the JSON object returned my Lambda function.
My function returns some JSON like this:
{
"id": "1234",
"name": "Foo Barstein"
}
I would like the template to output something like this:
{
"id": "1234",
"name": "Foo Barstein",
"href": "https://example.tld/thingy/1234"
}
And my mapping template looks like this:
#set($thingy = $input.json('$'))
#set($thingy.href = "https://example.tld/thingy/$thingy.id")
$thingy
However, my template outputs the unmodified $thingy, without the href I have tried to add.
I've read the VTL user guide, but to no avail.
Something like this has worked for me:
#set($body = $input.path('$'))
#set($body.href = "https://example.tld/thingy/$body.id")
$input.json('$')
There is no easy way to achieve this but you can workaround it:
## Mapping template
#set($body = $input.body)
#set($id = $input.json('$.id'))
{
"custom": {
"href" : "https://example.tld/thingy/$id"
},
"body": $body
}
And then merge all the keys in AWS.Lambda (if you use Lambda):
## Lambda handler
exports.handler = function(event, context) {
const requestParams = Object.assign({}, event.body, event.custom);
// ... function code
}
And requestParams will be what you want.
Following could do the trick. Beware, untested!
{
#set($payload = $util.parseJson($input.json('$')))
#set($body = "{
#foreach ($mapEntry in $payload.entrySet())
""$mapEntry.key"": ""$mapEntry.value"",
#end
""href"": ""$payload.id""
}")
$body
}

Paypal Rest api: How to delete a billing plan?

The paypal developer documentation explains the steps to create and activate a Billing plan.
Is there a way to delete a billing plan?
An alternative way of deleting a BillingPlan (as per the original question) is to submit a patch request. Unfortunately this isn't too clear from looking at the API docs: https://developer.paypal.com/docs/api/payments.billing-plans/#plan_update
You want to patch the state of the BillingPlan into DELETED:
[
{
"path": "/",
"value": {
"state": "DELETED"
},
"op": "replace"
}
]
Once patched, the deleted plan no longer shows up when you list all available plans via /v1/payments/billing-plans
There is a way to DELETE a Billing Plan.
If you see the samples in the REST-PHP-SDK, there is a file named DeletePlan.php which has the code to delete the billing plan.
It goes something like this:
$createdPlan = require 'CreatePlan.php';
use PayPal\Api\Plan;
try {
$result = $createdPlan->delete($apiContext);
} catch (Exception $ex) {
ResultPrinter::printError("Deleted a Plan", "Plan", $createdPlan->getId(), null, $ex);
exit(1);
}
ResultPrinter::printResult("Deleted a Plan", "Plan", $createdPlan->getId(), null, null);
return $createdPlan;
This worked for me. Hope this helps.
Thanks #smiling_warrior.
For the python API https://github.com/paypal/PayPal-Python-SDK/blob/master/samples/subscription/billing_agreements/replace.py
I used:
a=paypalrestsdk.BillingPlan.find("P-98072754CC611563JLOGIIYA")
a.replace([{"op": "replace","path": "/","value": {"state":"DELETED"}}])
Or delete all:
allplans = paypalrestsdk.BillingPlan.all()
for plan in allplans.plans:
a=paypalrestsdk.BillingPlan.find(plan.id)
a.replace([{"op": "replace","path": "/","value": {"state":"DELETED"}}])
As a complementary information about #maxxon15 answer, here's the actual code that does the DELETE on the PHP SDK :
public function delete($apiContext = null, $restCall = null)
{
ArgumentValidator::validate($this->getId(), "Id");
$patchRequest = new PatchRequest();
$patch = new Patch();
$value = new PayPalModel('{
"state":"DELETED"
}');
$patch->setOp('replace')
->setPath('/')
->setValue($value);
$patchRequest->addPatch($patch);
return $this->update($patchRequest, $apiContext, $restCall);
}
So in other terms, it simply does an update (PATCH) to the billing endpoint, as stated by #smiling-warrior
[
{
"path": "/",
"value": {
"state": "DELETED"
},
"op": "replace"
}
]

Get all file names from a Github repo through the Github API

Is it possible to get all the file names from repository using the GitHub API?
I'm currently trying to tinker this using PyGithub, but I'm totally ok with manually doing the request as long as it works.
My algorithm so far is:
Get the user repo names
Get the user repo that matches a certain description
??? get repo file names?
This will have to be relative to a particular commit, as some files may be present in some commits and absent in others, so before you can look at files you'll need to use something like List commits on a repository:
GET /repos/:owner/:repo/commits
If you're just interested in the latest commit on a branch you can set the sha parameter to the branch name:
sha string SHA or branch to start listing commits from.
Once you have a commit hash, you can inspect that commit
GET /repos/:owner/:repo/git/commits/:sha
which should return something like this (truncated from GitHub's documentation):
{
"sha": "...",
"...",
"tree": {
"url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb",
"sha": "691272480426f78a0138979dd3ce63b77f706feb"
},
"...": "..."
}
Look at the hash of its tree, which is essentially its directory contents. In this case, 691272480426f78a0138979dd3ce63b77f706feb. Now we can finally request the contents of that tree:
GET /repos/:owner/:repo/git/trees/:sha
The output from GitHub's example is
{
"sha": "9fb037999f264ba9a7fc6274d15fa3ae2ab98312",
"url": "https://api.github.com/repos/octocat/Hello-World/trees/9fb037999f264ba9a7fc6274d15fa3ae2ab98312",
"tree": [
{
"path": "file.rb",
"mode": "100644",
"type": "blob",
"size": 30,
"sha": "44b4fc6d56897b048c772eb4087f854f46256132",
"url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/44b4fc6d56897b048c772eb4087f854f46256132"
},
{
"path": "subdir",
"mode": "040000",
"type": "tree",
"sha": "f484d249c660418515fb01c2b9662073663c242e",
"url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/f484d249c660418515fb01c2b9662073663c242e"
},
{
"path": "exec_file",
"mode": "100755",
"type": "blob",
"size": 75,
"sha": "45b983be36b73c0788dc9cbcb76cbb80fc7bb057",
"url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/45b983be36b73c0788dc9cbcb76cbb80fc7bb057"
}
]
}
As you can see, we have some blobs, which correspond to files, and some additional trees, which correspond to subdirectories. You may want to do this recursively.
You can use Github git trees
https://api.github.com/repos/[USER]/[REPO]/git/trees/[BRANCH]?recursive=1
Repo
https://github.com/deeja/bing-maps-loader
Api Call
https://api.github.com/repos/deeja/bing-maps-loader/git/trees/master?recursive=1
which returns
{
sha: "55382e87889ccb4c173bc99a42cc738358fc253a",
url: "https://api.github.com/repos/deeja/bing-maps-loader/git/trees/55382e87889ccb4c173bc99a42cc738358fc253a",
tree: [
{
path: "README.md",
mode: "100644",
type: "blob",
sha: "41ceefc1262bb80a25529342ee3ec2ec7add7063",
size: 3196,
url: "https://api.github.com/repos/deeja/bing-maps-loader/git/blobs/41ceefc1262bb80a25529342ee3ec2ec7add7063"
},
{
path: "index.js",
mode: "100644",
type: "blob",
sha: "a81c94f70d1ca2a0df02bae36eb2aa920c7fb20e",
size: 1581,
url: "https://api.github.com/repos/deeja/bing-maps-loader/git/blobs/a81c94f70d1ca2a0df02bae36eb2aa920c7fb20e"
},
{
path: "package.json",
mode: "100644",
type: "blob",
sha: "45f24dcb7a457b14fede4cb907e957600882b340",
size: 595,
url: "https://api.github.com/repos/deeja/bing-maps-loader/git/blobs/45f24dcb7a457b14fede4cb907e957600882b340"
}
],
truncated: false
}
Much eaiser now with the graphql api, you can get it all in a single query
first you get your repo:
query {
repository(name: "MyRepo" owner: "mylogin"){
}
}
then you get its defaultBranchRef to make life easy
defaultBranchRef{
}
Now all a branch ref really is, is just a pointer to a commit, and since graphql is strongly typed (and refs can be different things) we need to let it know it is a commit,
target{
...on Commit {
}
}
so target is what our ref is pointing to, and we say "if its a commit, do this"
and what should it do?
it should get the most recent commit (since that will have the latest files in the repo)
so to do that we query history
history(first: 1 until: "2019-10-08T00:00:00"){
nodes{
}
}
now inside of nodes we are inside of our commit and now we can see the files,
the files in a commits pointer are really just a pointer to a tree, and a tree just has entries, which can be objects of either type Tree, or type blob
entries that represent files are known as blobs, but since we dont do anything with them but list their names, you dont even need to know that
but its important to know that trees are also entries, so if you find a tree you need to dig in deeper, but you can only go a pre defined amount of levels deep.
tree{
entries {
name
object {
...on Tree{
entries{
name
object {
...on Tree{
entries{
name
}
}
}
}
}
}
}
}
now to put it all together:
query{
repository(owner: "MyLogin", name: "MyRepo") {
defaultBranchRef {
target {
... on Commit {
history(first: 1 until: "2019-10-08T00:00:00") {
nodes {
tree {
entries {
name
object {
... on Tree {
entries {
name
object{
...on Tree{
entries{
name
object{
...on Tree{
entries{
name
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
As Dan mentioned: github trees
See working example below
import requests
user = "grumbach"
repo = "ft_ping"
url = "https://api.github.com/repos/{}/{}/git/trees/master?recursive=1".format(user, repo)
r = requests.get(url)
res = r.json()
for file in res["tree"]:
print(file["path"])
For the sake of simplicity I omitted error management, velociraptors are extinct anyway…
Use gh api for authenticated HTTP request to the GitHub API
in one line
gh api -X GET /repos/octocat/Hello-World/commits | grep -E -o ".{0,0}\[{\"sha\":\".{0,40}" | sed 's/\[{\"sha\":\"//' | xargs -I {} gh api -X GET /repos/octocat/Hello-World/commits/{} | grep -E -o "\"filename\":\".*?\""
Or in two steps
Get commits sha
gh api -X GET /repos/octocat/Hello-World/commits | grep -E -o ".{0,0}\[{\"sha\":\".{0,40}" | sed 's/\[{\"sha\":\"//' >> ~/commits
List file names
xargs < ~/commits -I {} gh api -X GET /repos/octocat/Hello-World/commits/{} | grep -E -o "\"filename\":\".*?\""