or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# JSON5

1

2

JSON5 is a JavaScript library that provides parsing and serialization functionality for the JSON5 data interchange format. JSON5 is a superset of JSON that includes ECMAScript 5.1 syntax enhancements, making configuration files and data structures more human-readable and maintainable.

3

4

## Package Information

5

6

- **Package Name**: json5

7

- **Package Type**: npm

8

- **Language**: JavaScript with TypeScript definitions

9

- **Installation**: `npm install json5`

10

11

## Core Imports

12

13

```typescript

14

import { parse, stringify } from 'json5';

15

```

16

17

For CommonJS:

18

19

```javascript

20

const JSON5 = require('json5');

21

// Access via: JSON5.parse, JSON5.stringify

22

```

23

24

## Basic Usage

25

26

```typescript

27

import { parse, stringify } from 'json5';

28

29

// Parse JSON5 string

30

const data = parse(`{

31

// comments are allowed

32

unquoted: 'and you can quote me on that',

33

singleQuotes: 'I can use "double quotes" here',

34

lineBreaks: "Look, Mom! \\

35

No \\n's!",

36

hexadecimal: 0xdecaf,

37

leadingDecimalPoint: .8675309,

38

andTrailing: 8675309.,

39

positiveSign: +1,

40

trailingComma: 'in objects',

41

andIn: ['arrays',],

42

}`);

43

44

// Convert JavaScript value to JSON5 string

45

const json5String = stringify(data, null, 2);

46

```

47

48

## Capabilities

49

50

### JSON5 Parsing

51

52

Parses a JSON5 string, constructing the JavaScript value or object described by the string.

53

54

```typescript { .api }

55

/**

56

* Parses a JSON5 string, constructing the JavaScript value or object described

57

* by the string.

58

* @template T The type of the return value.

59

* @param text The string to parse as JSON5.

60

* @param reviver A function that prescribes how the value originally produced

61

* by parsing is transformed before being returned.

62

* @returns The JavaScript value converted from the JSON5 string.

63

*/

64

function parse<T = any>(

65

text: string,

66

reviver?: ((this: any, key: string, value: any) => any) | null,

67

): T

68

```

69

70

**Usage Examples:**

71

72

```typescript

73

import { parse } from 'json5';

74

75

// Basic parsing

76

const config = parse(`{

77

name: 'MyApp',

78

version: '1.0.0',

79

debug: true,

80

}`);

81

82

// With reviver function

83

const data = parse(`{

84

created: "2023-01-01",

85

count: "42"

86

}`, (key, value) => {

87

if (key === 'created') return new Date(value);

88

if (key === 'count') return parseInt(value);

89

return value;

90

});

91

```

92

93

### JSON5 Stringification

94

95

Converts a JavaScript value to a JSON5 string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

96

97

```typescript { .api }

98

/**

99

* Converts a JavaScript value to a JSON5 string.

100

* @param value The value to convert to a JSON5 string.

101

* @param replacer A function that alters the behavior of the stringification

102

* process. If this value is null or not provided, all properties of the object

103

* are included in the resulting JSON5 string.

104

* @param space A String or Number object that's used to insert white space into

105

* the output JSON5 string for readability purposes. If this is a Number, it

106

* indicates the number of space characters to use as white space; this number

107

* is capped at 10 (if it is greater, the value is just 10). Values less than 1

108

* indicate that no space should be used. If this is a String, the string (or

109

* the first 10 characters of the string, if it's longer than that) is used as

110

* white space. If this parameter is not provided (or is null), no white space

111

* is used. If white space is used, trailing commas will be used in objects and

112

* arrays.

113

* @returns The JSON5 string converted from the JavaScript value.

114

*/

115

function stringify(

116

value: any,

117

replacer?: ((this: any, key: string, value: any) => any) | null,

118

space?: string | number | null,

119

): string

120

121

/**

122

* Converts a JavaScript value to a JSON5 string.

123

* @param value The value to convert to a JSON5 string.

124

* @param replacer An array of String and Number objects that serve as a

125

* allowlist for selecting/filtering the properties of the value object to be

126

* included in the JSON5 string. If this value is null or not provided, all

127

* properties of the object are included in the resulting JSON5 string.

128

* @param space A String or Number object that's used to insert white space into

129

* the output JSON5 string for readability purposes. If this is a Number, it

130

* indicates the number of space characters to use as white space; this number

131

* is capped at 10 (if it is greater, the value is just 10). Values less than 1

132

* indicate that no space should be used. If this is a String, the string (or

133

* the first 10 characters of the string, if it's longer than that) is used as

134

* white space. If this parameter is not provided (or is null), no white space

135

* is used. If white space is used, trailing commas will be used in objects and

136

* arrays.

137

* @returns The JSON5 string converted from the JavaScript value.

138

*/

139

function stringify(

140

value: any,

141

replacer: (string | number)[],

142

space?: string | number | null,

143

): string

144

145

/**

146

* Converts a JavaScript value to a JSON5 string.

147

* @param value The value to convert to a JSON5 string.

148

* @param options An object specifying options.

149

* @returns The JSON5 string converted from the JavaScript value.

150

*/

151

function stringify(value: any, options: StringifyOptions): string

152

```

153

154

**Usage Examples:**

155

156

```typescript

157

import { stringify } from 'json5';

158

159

const data = {

160

name: 'MyApp',

161

version: '1.0.0',

162

debug: true,

163

features: ['auth', 'api', 'ui']

164

};

165

166

// Basic stringification

167

const json5 = stringify(data);

168

169

// With formatting

170

const formatted = stringify(data, null, 2);

171

172

// With replacer function

173

const filtered = stringify(data, (key, value) => {

174

if (key === 'debug') return undefined; // exclude debug

175

return value;

176

}, 2);

177

178

// With property allowlist

179

const limited = stringify(data, ['name', 'version'], 2);

180

181

// With options object (including custom quote character)

182

const customQuotes = stringify(data, {

183

space: 2,

184

quote: "'"

185

});

186

```

187

188

### Node.js require() Support

189

190

Enable JSON5 file support in Node.js require() statements by registering the .json5 file extension.

191

192

```javascript { .api }

193

/**

194

* Register JSON5 file extension with Node.js require() system.

195

* This extends Node.js to automatically parse .json5 files when required.

196

*/

197

require('json5/lib/register');

198

```

199

200

**Usage Example:**

201

202

```javascript

203

// Register JSON5 support

204

require('json5/lib/register');

205

206

// Now you can require JSON5 files directly

207

const config = require('./config.json5');

208

```

209

210

### Command Line Interface

211

212

JSON5 provides a CLI tool for converting JSON5 to JSON and validating JSON5 syntax.

213

214

**Installation:**

215

```bash

216

npm install --global json5

217

```

218

219

**Usage:**

220

```bash

221

json5 [options] <file>

222

```

223

224

If `<file>` is not provided, then STDIN is used.

225

226

**CLI Options:**

227

- `-s, --space`: The number of spaces to indent or `t` for tabs

228

- `-o, --out-file [file]`: Output to the specified file, otherwise STDOUT

229

- `-v, --validate`: Validate JSON5 but do not output JSON

230

- `-c, --convert`: (Legacy) Convert input file to .json extension when no output file specified

231

- `-V, --version`: Output the version number

232

- `-h, --help`: Output usage information

233

234

**Examples:**

235

```bash

236

# Convert JSON5 file to JSON

237

json5 config.json5

238

239

# Convert with formatting

240

json5 -s 2 config.json5

241

242

# Validate JSON5 syntax

243

json5 -v config.json5

244

245

# Convert and save to file

246

json5 -o config.json config.json5

247

248

# Convert and auto-save as .json file (legacy option)

249

json5 -c config.json5

250

```

251

252

## Types

253

254

```typescript { .api }

255

interface StringifyOptions {

256

/**

257

* A function that alters the behavior of the stringification process, or an

258

* array of String and Number objects that serve as a allowlist for

259

* selecting/filtering the properties of the value object to be included in

260

* the JSON5 string. If this value is null or not provided, all properties

261

* of the object are included in the resulting JSON5 string.

262

*/

263

replacer?:

264

| ((this: any, key: string, value: any) => any)

265

| (string | number)[]

266

| null

267

268

/**

269

* A String or Number object that's used to insert white space into the

270

* output JSON5 string for readability purposes. If this is a Number, it

271

* indicates the number of space characters to use as white space; this

272

* number is capped at 10 (if it is greater, the value is just 10). Values

273

* less than 1 indicate that no space should be used. If this is a String,

274

* the string (or the first 10 characters of the string, if it's longer than

275

* that) is used as white space. If this parameter is not provided (or is

276

* null), no white space is used. If white space is used, trailing commas

277

* will be used in objects and arrays.

278

*/

279

space?: string | number | null

280

281

/**

282

* A String representing the quote character to use when serializing

283

* strings.

284

*/

285

quote?: string | null

286

}

287

```

288

289

## JSON5 Format Features

290

291

JSON5 extends JSON with the following ECMAScript 5.1 features:

292

293

### Objects

294

- Object keys may be unquoted identifiers

295

- Objects may have trailing commas

296

297

### Arrays

298

- Arrays may have trailing commas

299

300

### Strings

301

- Strings may be single quoted

302

- Strings may span multiple lines by escaping newlines

303

- Strings may include character escapes

304

305

### Numbers

306

- Numbers may be hexadecimal (0x...)

307

- Numbers may have leading or trailing decimal points

308

- Numbers may be IEEE 754 positive infinity, negative infinity, and NaN

309

- Numbers may begin with an explicit plus sign

310

311

### Comments

312

- Single-line comments (`//`) and multi-line comments (`/* */`) are allowed

313

314

### White Space

315

- Additional white space characters are allowed

316

317

## Error Handling

318

319

Both `parse()` and `stringify()` functions may throw errors:

320

321

- **Parse errors**: Thrown when JSON5 syntax is invalid

322

- **Stringify errors**: Thrown when values cannot be serialized (e.g., circular references)

323

- **CLI errors**: Exit codes indicate validation or conversion failures

324

325

Always wrap JSON5 operations in try-catch blocks for production usage:

326

327

```typescript

328

import { parse, stringify } from 'json5';

329

330

try {

331

const data = parse(json5String);

332

const output = stringify(data);

333

} catch (error) {

334

console.error('JSON5 operation failed:', error.message);

335

}

336

```