|
| 1 | +# Using GPT-3 to figure out jq recipes |
| 2 | + |
| 3 | +I like [jq](https://stedolan.github.io/jq/), but I always have to think pretty hard about how to construct the right syntax for it. |
| 4 | + |
| 5 | +Here's how I used the [GPT-3 playground](https://simonwillison.net/2022/Jun/5/play-with-gpt3/) to solve a simple `jq` problem. |
| 6 | + |
| 7 | +I wanted to sum up the total number of comments in JSON that looks like this (truncated example): |
| 8 | + |
| 9 | +```json |
| 10 | +[ |
| 11 | + { |
| 12 | + "id": "31195431", |
| 13 | + "title": "Automatically filing issues when tracked file content changes", |
| 14 | + "url": "https://simonwillison.net/2022/Apr/28/issue-on-changes/", |
| 15 | + "dt": "2022-04-28T17:29:37", |
| 16 | + "points": 14, |
| 17 | + "submitter": "simonw", |
| 18 | + "commentsUrl": "https://news.ycombinator.com/item?id=31195431", |
| 19 | + "numComments": 4 |
| 20 | + }, |
| 21 | + { |
| 22 | + "id": "31185496", |
| 23 | + "title": "Parallel SQL Queries in Datasette", |
| 24 | + "url": "https://simonwillison.net/2022/Apr/27/parallel-queries/", |
| 25 | + "dt": "2022-04-27T20:39:50", |
| 26 | + "points": 1, |
| 27 | + "submitter": "frogger8", |
| 28 | + "commentsUrl": "https://news.ycombinator.com/item?id=31185496", |
| 29 | + "numComments": 3 |
| 30 | + } |
| 31 | +] |
| 32 | +``` |
| 33 | +The first prompt I tried was: |
| 34 | + |
| 35 | +``` |
| 36 | +# Use jq to calculate the sum of the num field in each object in this array: |
| 37 | +
|
| 38 | +echo '[ |
| 39 | + {"num": 1}, |
| 40 | + {"num": 2} |
| 41 | +]' | jq |
| 42 | +``` |
| 43 | +I hinted at how I wanted to do this by piping to `jq` but without any argument. |
| 44 | + |
| 45 | +GPT-3 completed that to: |
| 46 | + |
| 47 | +``` |
| 48 | +echo '[ |
| 49 | + {"num": 1}, |
| 50 | + {"num": 2} |
| 51 | +]' | jq 'reduce .[] as $item (0; . + $item.num)' |
| 52 | +``` |
| 53 | +... then a bunch more output that gave further examples, which I ignored |
| 54 | + |
| 55 | +This is good - that solution works! Here's what happens when I run it: |
| 56 | + |
| 57 | +``` |
| 58 | +~ % echo '[ |
| 59 | + {"num": 1}, |
| 60 | + {"num": 2} |
| 61 | +]' | jq 'reduce .[] as $item (0; . + $item.num)' |
| 62 | +3 |
| 63 | +``` |
| 64 | +But I'm not a big fan of `reduce` in general - I always have to think a bit about what it's actually doing. |
| 65 | + |
| 66 | +So I added a follow-up prompt: |
| 67 | + |
| 68 | +``` |
| 69 | +Now do that without using reduce: |
| 70 | +``` |
| 71 | +And GPT-3 replied: |
| 72 | +``` |
| 73 | +echo '[ |
| 74 | + {"num": 1}, |
| 75 | + {"num": 2} |
| 76 | +]' | jq '. | map(.num) | add' |
| 77 | +``` |
| 78 | +This is the exact solution I was looking for. |
0 commit comments