Skip to content
This repository has been archived by the owner on Mar 3, 2022. It is now read-only.

Commit

Permalink
Add dot feature
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Aug 30, 2018
1 parent cc900da commit 988d4dd
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ $ echo '{"key":"value"}' | xx
You can get access to JSON by `this` keyword:
```
$ echo '{"foo": [{"bar": "value"}]}' | xx 'this.foo[0].bar'
"value"
value
```

### Chain

You can pass any number of code blocks for reducing JSON:
```
$ echo '{"foo": [{"bar": "value"}]}' | xx 'this.foo' 'this[0]' 'this.bar'
"value"
value
```

### Formatting
Expand Down Expand Up @@ -99,6 +99,15 @@ By the way, xx has shortcut for `Object.keys(this)`. Previous example can be rew
$ echo '{"foo": 1, "bar": 2}' | xx ?
```

### Dot

It is possible to omit `this` keyword:

```
$ echo '{"foo": "bar"}' | xx .foo[0].bar
value
```

## Related

* [fx](https://github.com/antonmedv/fx) – original `fx` package
Expand Down
21 changes: 19 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ func main() {
return
}

if value.IsString() {
fmt.Println(value)
return
}

i, err := value.Export()
if err != nil {
fatal(err)
Expand All @@ -66,9 +71,13 @@ func reduce(value otto.Value, code string) (otto.Value, error) {
if err := vm.Set("json", value); err != nil {
fatal(err)
}
switch code {
case "?":
switch {
case code == "?":
code = "Object.keys(json)"
case code == ".":
code = "(function () {return this;}).call(json)"
case len(code) > 1 && code[0] == '.':
code = fmt.Sprintf(`(function () {return this%v;}).call(json)`, code)
default:
code = fmt.Sprintf(`(function () {return %v;}).call(json)`, code)
}
Expand All @@ -81,6 +90,8 @@ func reduce(value otto.Value, code string) (otto.Value, error) {

func usage() {
fmt.Fprintf(os.Stderr, `
Command-line JSON processing tool
Usage
$ xx [code ...]
Expand All @@ -94,6 +105,12 @@ func usage() {
$ echo '{"items": ["one", "two"]}' | xx 'this.items' 'this[1]'
"two"
$ echo '{"foo": 1, "bar": 2}' | xx ?
["foo", "bar"]
$ echo '{"key": "value"}' | xx .key
value
`)
}

Expand Down

0 comments on commit 988d4dd

Please sign in to comment.