Hacker News new | past | comments | ask | show | jobs | submit login

Built into Powershell:

    > @{ hello = 'world' } | ConvertTo-Json
    > { "hello": "world" }



Not only its built in, but syntax is on another level, i.e. you don't need to learn special syntax if you know PowerShell. This thing alone makes pwsh worth it instead of using number of other tools.

    @{ Hello = 'world'; array = 1..10; object = @{ date = Get-Date } } | ConvertTo-Json
 
    {
      "array": [
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10
      ],
      "object": {
        "date": "2024-07-03T21:07:21.6562053+02:00"
      },
      "Hello": "world"
    }


That is pretty cool, and I wish such features were common in regular UNIX shells.

For good measure, this is how you might do the same with jb:

    $ jb Hello=world array:number[]@<(seq 10) object:json@<(date=$(date -Iseconds) jb @date)
    {"Hello":"world","array":[1,2,3,4,5,6,7,8,9,10],"object":{"date":"2024-07-03T19:26:36+00:00"}}
Alternatively, using the :{} object entry syntax:

    jb Hello=world array:number[]@<(seq 10) object:{}=date=$(date -Iseconds)
    {"Hello":"world","array":[1,2,3,4,5,6,7,8,9,10],"object":{"date":"2024-07-03T19:30:26+00:00"}}


Powershell has the upper hand here!

Still, bash can try to keep up using json.bash. :)

    $ source json.bash
    $ declare -A greeting=([Hello]=World)
    $ json ...@greeting:{}
    {"Hello":"World"}
... is splatting the greeting associative array entries into the object created by the json call.

Without the ... the greeting would be a nested object. Probably more clear with multiple entries:

    $ declare -A greeting=([Hello]=World [How]="are you?")
    $ json @greeting:{}   
    {"greeting":{"Hello":"World","How":"are you?"}}
Vs:

    $ json ...@greeting:{}                                
    {"Hello":"World","How":"are you?"}


    $h=@{x=1; y=2}; $h + @{z=3} | ConvertTo-Json

    {        
      "y": 2,
      "z": 3,
      "x": 1 
    }
You can even use [ordered]$h to make keys not go random place.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: