Skip to content

Instantly share code, notes, and snippets.

@arc279
Created June 28, 2022 08:51
Show Gist options
  • Save arc279/ab488aac322e9bf5b6247fa99ccb5e62 to your computer and use it in GitHub Desktop.
Save arc279/ab488aac322e9bf5b6247fa99ccb5e62 to your computer and use it in GitHub Desktop.
urlparse for jq
def mergeHeader:
[
"scheme",
"user",
"password",
"domain",
"path",
"querystring",
"fragment"
] as $header
| [ ., $header]
| transpose
| map({(.[1]): .[0]})
| add
;
def urlparse:
#------------------------
split("//")
as [$scheme, $s1]
#------------------------
| $s1 | split("@")
| (
if length == 2 then
(.[1] as $d | .[0] | split(":") | [.[0], .[1], $d])
else
[null, null, .[0]]
end
)
as [$user, $password, $s2]
#------------------------
| $s2 | split("#")
| (
if length == 1 then
[.[], null]
else
.
end
)
as [$s3, $fragment]
#------------------------
| $s3 | split("?")
| (
if length == 1 then
[.[], null]
else
.
end
)
as [$s4, $querystring]
#------------------------
| $s4 | split("/")
| (
if length == 1 then
[.[0], null]
else
[.[0], (.[1:]|join("/"))]
end
)
as [$domain, $path]
#------------------------
| [
$scheme,
$user,
$password,
$domain,
$path,
$querystring,
$fragment
]
| mergeHeader
;
[
"https://example.com",
"https://user:[email protected]",
"https://[email protected]",
"https://example.com/hoge",
"https://example.com/hoge/hoge2",
"https://example.com/hoge/hoge2/",
"https://example.com/hoge?q=123",
"https://example.com/hoge/?q=123",
"https://example.com/hoge?q=123#fragment",
"https://example.com/hoge/?q=123#fragment",
"https://example.com/hoge#fragment",
"https://example.com/hoge/#fragment"
][]
| . as $u | [ $u, urlparse ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment