|
| 1 | +function Get-JsonLD { |
| 2 | + <# |
| 3 | + .SYNOPSIS |
| 4 | + Gets JSON-LD data from a given URL. |
| 5 | + .DESCRIPTION |
| 6 | + Gets JSON Linked Data from a given URL. |
| 7 | + |
| 8 | + This is a format used by many websites to provide structured data about their content. |
| 9 | + .EXAMPLE |
| 10 | + # Want to get information about a movie? Linked Data to the rescue! |
| 11 | + Get-JsonLD -Url https://www.imdb.com/title/tt0211915/ |
| 12 | + .EXAMPLE |
| 13 | + # Want information about an article? Lots of news sites use this format. |
| 14 | + Get-JsonLD https://www.thebulwark.com/p/mahmoud-khalil-immigration-detention-first-amendment-free-speech-rights |
| 15 | + .EXAMPLE |
| 16 | + # Want to get information about a schema? |
| 17 | + jsonld https://schema.org/Movie |
| 18 | + # Get-JSONLD will output the contents of a `@Graph` object if no `@type` is found. |
| 19 | + #> |
| 20 | + [Alias('jsonLD','json-ld')] |
| 21 | + param( |
| 22 | + # The URL that may contain JSON-LD data |
| 23 | + [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] |
| 24 | + [Uri] |
| 25 | + $Url |
| 26 | + ) |
| 27 | + |
| 28 | + begin { |
| 29 | + $linkedDataRegex = [Regex]::new(@' |
| 30 | +(?<HTML_LinkedData> |
| 31 | +<script # Match <script tag |
| 32 | +\s{1,} # Then whitespace |
| 33 | +type= # Then the type= attribute (this regex will only match if it is first) |
| 34 | +[\"\'] # Double or Single Quotes |
| 35 | +application/ld\+json # The type that indicates linked data |
| 36 | +[\"\'] # Double or Single Quotes |
| 37 | +[^>]{0,} # Match anything until the end of the start tag |
| 38 | +\> # Match the end of the start tag |
| 39 | +(?<JsonContent>(?:.|\s){0,}?(?=\z|</script>)) # Anything until the end tag is JSONContent |
| 40 | +) |
| 41 | +'@, 'IgnoreCase,IgnorePatternWhitespace','00:00:00.1') |
| 42 | + } |
| 43 | + |
| 44 | + process { |
| 45 | + $restResponse = Invoke-RestMethod -Uri $Url |
| 46 | + foreach ($match in $linkedDataRegex.Matches("$restResponse")) { |
| 47 | + foreach ($jsonObject in |
| 48 | + $match.Groups['JsonContent'].Value | |
| 49 | + ConvertFrom-Json |
| 50 | + ) { |
| 51 | + if ($jsonObject.'@type') { |
| 52 | + $schemaType = $jsonObject.'@context',$jsonObject.'@type' -ne '' -join '/' |
| 53 | + $jsonObject.pstypenames.insert(0, $schemaType) |
| 54 | + $jsonObject |
| 55 | + } elseif ($jsonObject.'@graph') { |
| 56 | + foreach ($graphObject in $jsonObject.'@graph') { |
| 57 | + if ($graphObject.'@type') { |
| 58 | + $graphObject.pstypenames.insert(0, $graphObject.'@type') |
| 59 | + } |
| 60 | + $graphObject |
| 61 | + } |
| 62 | + } else { |
| 63 | + $jsonObject |
| 64 | + } |
| 65 | + |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments