Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,27 @@ Things to note:

Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change.

### Usage

- Read JSON file:

```sh
node json-to-go.js sample.json
```

- Read JSON file from stdin:

```sh
node json-to-go.js < sample.json
cat sample.json | node json-to-go.js
```

- Read large JSON file from stdin:

```sh
node json-to-go.js --big < sample.json
cat sample.json | node json-to-go.js --big
```

### Credits

Expand Down
72 changes: 49 additions & 23 deletions json-to-go.js
Original file line number Diff line number Diff line change
Expand Up @@ -494,27 +494,53 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
}

if (typeof module != 'undefined') {
if (!module.parent) {
if (process.argv.length > 2 && process.argv[2] === '-big') {
bufs = []
process.stdin.on('data', function(buf) {
bufs.push(buf)
})
process.stdin.on('end', function() {
const json = Buffer.concat(bufs).toString('utf8')
process.stdout.write(jsonToGo(json).go)
})
} else if (process.argv.length === 3) {
const fs = require('fs');
const json = fs.readFileSync(process.argv[2], 'utf8');
process.stdout.write(jsonToGo(json).go)
} else {
process.stdin.on('data', function(buf) {
const json = buf.toString('utf8')
process.stdout.write(jsonToGo(json).go)
})
}
} else {
module.exports = jsonToGo
}
if (!module.parent) {
let bigstdin = false
let filename = null

process.argv.forEach((val, index) => {
if (index < 2)
return

if (!val.startsWith('-')) {
filename = val
return
}

const argument = val.replace(/-/g, '')
if (argument === "big")
bigstdin = true
else {
console.error(`Unexpected argument ${val} received`)
process.exit(1)
}
})

if (filename) {
const fs = require('fs');
const json = fs.readFileSync(filename, 'utf8');
process.stdout.write(jsonToGo(json).go)
return
}

if (bigstdin) {
bufs = []
process.stdin.on('data', function(buf) {
bufs.push(buf)
})
process.stdin.on('end', function() {
const json = Buffer.concat(bufs).toString('utf8')
process.stdout.write(jsonToGo(json).go)
})
return
}

// read from stdin
process.stdin.on('data', function(buf) {
const json = buf.toString('utf8')
process.stdout.write(jsonToGo(json).go)
})
} else {
module.exports = jsonToGo
}
}