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
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,19 +177,26 @@ const json = await readJSON('www.url.com/file.json')
#### writeJSON

```ts
writeJSON(path: string, data: any): void
writeJSON(path: string, data: any, replacer?: any, space?: string | number): void


```

Args:

* **path**: path to a local JSON file
* **data**: data to store as JSON
* **replacer**: [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#parameters) function that transforms the results or an array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified
* **space**: adds indentation, white space, and line break characters to the to the JSON text to make it easier to read.


Usage:

```ts
const data = { age: 40 }
await writeJSON('./path/to/file.json', data)

await writeJSON('./path/to/file-with-indentation', data, null, 2)
```

### XLSX
Expand Down
4 changes: 4 additions & 0 deletions examples/json/json-indent-test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"prices": "$20",
"name": "table"
}
4 changes: 2 additions & 2 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ export async function readJSON(path: string) {
return JSON.parse(text)
}

export async function writeJSON(path: string, data: any) {
await Deno.writeTextFile(path, JSON.stringify(data))
export async function writeJSON(path: string, ...args: Parameters<typeof JSON.stringify>) {
await Deno.writeTextFile(path, JSON.stringify(...args))
}

export async function readJSONFromURL(url: string) {
Expand Down
12 changes: 12 additions & 0 deletions tests/json-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { readJSON, writeJSON } from '../src/json.ts'

const jsonReadPath = './examples/json/data.json'
const jsonWritePath = './examples/json/json-test.json'
const jsonIndentWritePath = './examples/json/json-indent-test.json'

Deno.test("reads a json file", async () => {
const json = await readJSON(jsonReadPath)
Expand All @@ -18,5 +19,16 @@ Deno.test("writes a json file", async () => {
await writeJSON(jsonWritePath, data)
const json = await readJSON(jsonWritePath)

assertObjectMatch(json, { prices: "$20", name: "table" });
})

Deno.test("writes a json file with space indent", async () => {
const data = {
prices: '$20',
name: 'table'
}
await writeJSON(jsonIndentWritePath, data, null, 2)
const json = await readJSON(jsonIndentWritePath)

assertObjectMatch(json, { prices: "$20", name: "table" });
})