# JSON5 for Dart and Flutter: Complete Guide | JSON5.dev


Source: https://json5.dev/dart/

---

# JSON5 for Dart and Flutter

Read JSON5 config in Dart and Flutter with the long-established package for it, and learn exactly where it stops.

The `json5` package on pub.dev is a Dart port of the JavaScript reference parser. This guide reads its source, shows its API, loads a `.json5` asset in a Flutter app, and feeds the result to `json_serializable`.

You also get the catch: `SyntaxException` is not exported, so catching it takes a workaround. Other pub.dev packages are compared with their real versions, dates and scores, and every claim is marked as read from source or not run.

[Install](#installation) [Flutter Assets](#flutter-assets) [Errors](#errors)

![A JSON5 settings file flowing through a Dart parser into a typed Flutter settings object on a phone](https://json5.dev/img/hero/dart.png)

**TL;DR:** Run `dart pub add json5`, then call `json5Decode(text)` or `JSON5.parse(text)`. Version 0.8.2 (November 15, 2023) is the latest release and still the established JSON5 parser on pub.dev. It parses and writes JSON5 but has no reviver, no comment preservation, and its error class is not exported. Decode first, then hand the `Map` to a `json_serializable` `fromJson`.

[Installation](#installation) [API From Source](#api) [Types](#types) [Flutter Assets](#flutter-assets) [json\_serializable](#codegen) [Errors](#errors) [Other Packages](#packages) [Conformance](#conformance) [FAQ](#faq)

![Dart logo](https://json5.dev/images/tech/dart.svg)

## Installation

Dart has no built-in JSON5 support: `dart:convert` parses strict JSON only. The `json5` package on pub.dev fills the gap. It is published by the verified publisher `damphat.com`, and its README says it is "a ported version of" the JavaScript `json5` package that uses "the same algorithms", so it should behave like the reference parser.

`dart pub add json5 # in a Flutter project flutter pub add json5`

Package facts, read from the pub.dev API and the GitHub repository on November 29, 2026:

0.8.2

Latest version, published November 15, 2023

150/160

pub points, with 20 likes

25,420

Downloads in the last 30 days

MIT

License

The package has had twelve releases, from 0.5.0 on October 17, 2020 to 0.8.2. Its pubspec allows Dart `>=2.17.1 <4.0.0`, so it installs on current SDKs; the latest stable Dart we found was 3.14.1, dated November 17, 2026. pub.dev tags it for Dart and Flutter, on Android, iOS, Windows, Linux, macOS and web, and marks it null-safe, Dart 3 compatible and wasm-ready. The repository (damphat/json5-dart) has 13 stars and one open issue; the last push was February 23, 2025, a README edit. Treat it as finished and quiet, not abandoned and not actively developed.

![Dart logo](https://json5.dev/images/tech/dart.svg)

## The API, Read From Source

`lib/json5.dart` in version 0.8.2 exports exactly two ways to do each job. The static class `JSON5` mirrors the JavaScript names, and the top-level functions follow Dart naming. They call the same code.

Call

Same as

What it does

`JSON5.parse(String)`

`json5Decode(String)`

Parses JSON5 or JSON text and returns `dynamic`. Throws `SyntaxException` on bad input.

`JSON5.stringify(object, {space, toEncodable})`

`json5Encode(object, {space, toEncodable})`

Returns a JSON5 string. `space` is a number (capped at 10) or a string (first 10 characters).

`import 'package:json5/json5.dart'; void main() { final config = json5Decode(''' { // comments, unquoted keys and a trailing comma name: 'demo', ports: [8080, 8081,], } ''') as Map<String, dynamic>; print(config['name']); print(json5Encode(config)); }`

The package's own test suite fixes the output format, so these two results are asserted by its tests rather than guessed. Compact output has no spaces and no [trailing comma](https://json5.dev/glossary/#trailing-comma); pretty output indents and does add one:

`// json5Encode({'x': [1, 2]}) {x:[1,2]} // json5Encode({'x': [1, 2]}, space: 2) { x: [ 1, 2, ], }`

### What the writer does

-   **Keys.** A key that is a valid identifier is written bare. Anything else is quoted, so `{1: 1}` becomes `{'1':1}`. Non-string keys go through `toString()`.
-   **Strings.** The writer counts quote characters and picks the one that needs fewer escapes. With a tie, single quotes win, which the tests confirm (`'abc\0'`).
-   **Special numbers.** Numbers are written with `num.toString()`, so `double.nan` and the infinities come out as `NaN`, `Infinity` and `-Infinity`, all valid JSON5.
-   **Your own classes.** Anything that is not a `Map`, `List`, `Iterable`, string, number, bool or null goes to `toEncodable`. The default calls `toMap()`, then `toJson()`, then falls back to `toString()`. A class generated by `json_serializable` already has `toJson()`, so `json5Encode(user)` works with no extra code.
-   **Failures.** A circular structure throws a plain `Exception('Converting circular structure to JSON5')`, and a value nothing can encode throws `Exception('Cannot stringify ...')`.

### What is not there

The internal `parse()` function accepts a [reviver](https://json5.dev/glossary/#reviver), but the public wrappers always pass `null`, so there is no reviver callback. There is no option to reject duplicate keys: the parser assigns into a map, so the last value wins. There are no comments in the output, and none survive a [round trip](https://json5.dev/glossary/#round-trip). Strings containing the characters U+2028 or U+2029 make the parser call `print()` with a warning, so those two characters write a line to the console of your app (the source carries a FIXME about it).

![Structure icon](https://json5.dev/images/icons/structure.png)

## What Comes Back

Every parsed object is a `Map<String, dynamic>` and every array is a `List<dynamic>`; the source builds them with exactly those literals, and a regression test in the repository exists because an earlier release returned `Map<dynamic, dynamic>` and broke assignment to `Map<String, dynamic>`. That makes the result a drop-in input for `fromJson(Map<String, dynamic> json)`.

JSON5 text

Dart value

Basis

`0`, `42`, `-7`

`int`

Changelog 0.8.0 and the type assertions in `json5_test.dart`

`0.0`, `1.5`, `-90e+09`

`double`

Same test file

`NaN`, `Infinity`, `-Infinity`

`double.nan`, `double.infinity`, `-double.infinity`

Same test file

`0xFF`

Passed to `double.parse` in the source, so expect a `double`

Source only; we could not execute it

`'text'`, `"text"`

`String`, with `\x20` and `\u0123` escapes decoded

Test file

`null`, `true`, `false`

`null`, `bool`

Test file

Because `0` and `1` come back as `int` and `1.0` as `double`, a field typed `double` in a model needs the number written with a decimal point, or a `num` field, or `(json['x'] as num).toDouble()`. Test a model with a `double` field against a whole-number value before you ship it.

![Flutter logo](https://json5.dev/images/tech/flutter.png)

## Parsing Assets in Flutter

A Flutter app cannot open files by path the way a command-line tool does. It declares assets in `pubspec.yaml`, and loads them through an asset bundle. According to the Flutter documentation, each file is listed under `flutter:` then `assets:` (indentation matters), and a directory entry ending in `/` includes only the files directly inside it, not subdirectories; each subdirectory needs its own entry.

`# pubspec.yaml dependencies: flutter: sdk: flutter json5: ^0.8.2 flutter: assets: - assets/settings.json5`

`// assets/settings.json5 { // shown on the home screen title: 'Weather', refreshSeconds: 300, cities: ['Oslo', 'Lima',], }`

`rootBundle.loadString` from `package:flutter/services.dart` reads the text; the documentation recommends `DefaultAssetBundle.of(context)` inside widgets so tests can substitute a different bundle. Parse straight after loading:

`import 'package:flutter/services.dart' show rootBundle; import 'package:json5/json5.dart'; Future<Map<String, dynamic>> loadSettings() async { final text = await rootBundle.loadString('assets/settings.json5'); return json5Decode(text) as Map<String, dynamic>; }`

**Cost on the startup path.** The package is a direct port of the JavaScript lexer: a state machine that reads one character at a time and builds each token by string concatenation. We did not benchmark it, so we make no speed claim, but expect it to be slower than `jsonDecode`. For a settings file of a few kilobytes that is irrelevant. For a large data asset, measure on a low-end device, parse once and cache, or move the work off the UI isolate with `Isolate.run`. The parser also keeps its state in top-level variables, which is safe because parsing is synchronous and finishes before another call starts in the same isolate.

Ship JSON5 assets only where a person edits them. If the file is generated by your build, emit plain JSON and use `jsonDecode`; it is faster, needs no dependency and nobody will ever write a comment in it. The other half of that trade is covered in [Migrating from JSON](https://json5.dev/tutorials/migration-from-json/).

![Dart logo](https://json5.dev/images/tech/dart.svg)

## Typed Models With json\_serializable

Parsing gives you a `Map`; typed access comes from a model class. `json_serializable` (6.15.2, October 20, 2026, publisher `google.dev`, 160/160 pub points, about 4.48 million downloads in 30 days) generates the conversion code at build time. It never sees JSON5: the JSON5 parser produces the map, and the generated `fromJson` consumes it. Flutter's documentation sets it up with one command:

`flutter pub add json_annotation dev:build_runner dev:json_serializable dart run build_runner build --delete-conflicting-outputs`

`// lib/settings.dart import 'package:json_annotation/json_annotation.dart'; import 'package:json5/json5.dart'; part 'settings.g.dart'; @JsonSerializable() class Settings { Settings(this.title, this.refreshSeconds, this.cities); final String title; final int refreshSeconds; final List<String> cities; factory Settings.fromJson(Map<String, dynamic> json) => _$SettingsFromJson(json); Map<String, dynamic> toJson() => _$SettingsToJson(this); factory Settings.fromJSON5(String text) => Settings.fromJson(json5Decode(text) as Map<String, dynamic>); }`

The `part` line, the `fromJson` and `toJson` pair and the build command are the pattern from the Flutter documentation and the `json_serializable` README; the first build shows "Target of URI hasn't been generated" until the generator runs, which the documentation calls normal. Two points specific to JSON5:

-   **Unknown and missing keys.** The decoded map keeps every key the file contains, and nothing in the parser checks those keys against your model, so a typo such as `refreshSecond` is not caught at parse time. Keep a schema check in your tests ([schema validation guide](https://json5.dev/tutorials/schema-validation/)).
-   **Writing back.** `json5Encode(settings)` reaches the model through its `toJson()` because of the default `toEncodable` shown above. The result is JSON5 with no comments, so do not use it to rewrite a file a person maintains.

There is also a helper in the ecosystem, `json5_model` 5.0.1 (April 30, 2025, 140/160 pub points). Its pubspec describes it as generating Dart model classes from JSON files with one command, and it lists `json5` ^0.8.0 and `build_runner` as dependencies. We did not run it, so check its README before adopting it.

![Bug icon](https://json5.dev/images/icons/bug.png)

## Error Handling

Invalid input throws `SyntaxException`, defined in `lib/src/syntax_exception.dart`. It implements `Exception` and carries `message`, `lineNumber` and `columnNumber`. Its `toString()` prints `SyntaxException:` followed by the message, and the parser builds messages of three shapes:

`JSON5: invalid character 'x' at LINE:COLUMN JSON5: invalid end of input at LINE:COLUMN JSON5: invalid identifier character at LINE:COLUMN`

**The exception class is not exported.** `lib/json5.dart` has no `export` line, so `import 'package:json5/json5.dart'` does not give you `SyntaxException`. The package's own tests import it from `package:json5/src/syntax_exception.dart`. Doing the same in an application works today, but `src/` is private to the package and can change in any release.

Two workable patterns. The first catches `Exception`, which covers the parser and the writer, and reports the text. The second imports the private class, and should be confined to one file so a future change is a one-line fix:

`// Pattern 1: no private import Map<String, dynamic>? tryLoad(String text) { try { return json5Decode(text) as Map<String, dynamic>; } on Exception catch (e) { print('Bad json5 config: $e'); return null; } } // Pattern 2: the typed exception, with line and column. // The src import goes at the top of the file: import 'package:json5/src/syntax_exception.dart'; void report(String text) { try { json5Decode(text); } on SyntaxException catch (e) { print('line ${e.lineNumber}, column ${e.columnNumber}: ${e.message}'); } }`

Pattern 1 has one trap: a failed cast (`as Map<String, dynamic>` on a document whose root is an array) throws a `TypeError`, which is an `Error` and not an `Exception`, so it escapes the `on Exception` clause. Check the shape first with `if (value is! Map<String, dynamic>)`.

The parse-error tests show what is rejected: an empty string, `[,]`, `[1,,]`, `{1:1}` (a number is not a key), an unterminated string or comment, and `nul`. The shared list of errors across implementations is in the [error reference](https://json5.dev/errors/).

![Compare icon](https://json5.dev/images/icons/compare.png)

## Other Packages You Can Verify

A pub.dev search for "json5" returns a handful of unrelated names. These are the ones that parse or relate to JSON5, with figures from the pub.dev API on November 29, 2026.

Package

Version

Published

Pub points

Reads JSON5

Writes JSON5

Notes

**`json5`**

0.8.2

Nov 15, 2023

150/160

![Yes](https://json5.dev/images/icons/yes.png)

![Yes](https://json5.dev/images/icons/yes.png)

Port of the JavaScript parser; 25,420 downloads in 30 days

**`json5_plus`**

0.2.1

Nov 23, 2026

70/160

![Yes](https://json5.dev/images/icons/yes.png)

![Yes](https://json5.dev/images/icons/yes.png)

First release May 11, 2026; 184 downloads in 30 days; needs Dart 3.11.1 or newer

`jsonc`

0.0.3

Dec 23, 2022

150/160

![No](https://json5.dev/images/icons/no.png)

![No](https://json5.dev/images/icons/no.png)

Described as "JSON with comments and trailing commas", so a JSONC parser, not JSON5

### `json5_plus`

The newcomer, by publisher `greatlogic.com` (repository AndyKing42/json5\_plus). Its README advertises typed accessors, optional case-insensitive keys, a formatter that "guarantees an almost lossless reproduction" of input structure and comments, and an `$include` directive that pulls in another file with parameters. It also reports parse times within about 13 to 19 percent of `jsonDecode` on its own AOT benchmark, a figure we did not reproduce. The entry point is a `Json5` object:

`import 'package:json5_plus/json5_plus.dart'; void main() { final json = Json5.fromString('{ key: "value", /* comment */ }'); print(json.asString('key')); }`

That sample is the README's own. With a 0.x version number, 70 pub points and a first release in May 2026, it is promising but young; pin the version and test it against your own files. Its comment-preserving formatter is the capability the older package lacks, which matters for tools that rewrite a file a person maintains.

![Test icon](https://json5.dev/images/icons/test.png)

## Conformance and Honest Limits

The README claims the same behavior as the JavaScript package because it uses the same algorithm, and the source is consistent with it: `lib/src/parse.dart` is a character-at-a-time state machine with named lexer states such as `decimalFraction` and `hexadecimalInteger`. The repository's tests cover primitives, string escapes (`\b \f \v \r \n \t \\ \xNN \uNNNN`), separators and a list of malformed inputs. That is a reasonable smoke suite, and far short of the shared JSON5 conformance corpus; we have not run that corpus against this package.

**What we could and could not verify.** Everything above about the API, types and errors is read from the 0.8.2 source archive and its tests. We did not execute the Dart samples on this page, and we did not run the package's test suite, so we show only outputs that the package's own tests assert. Read [the conformance page](https://json5.dev/conformance/) for how other implementations compare, and test your own documents before relying on edge cases such as hex numbers or very large integers.

The package's README lists one limit itself: "Only serialize classes which implement List and Map". The `toEncodable` hook, added in 0.7.0, softens it, but a class without `toMap()` or `toJson()` is written as its `toString()` output, a string, with no warning.

## JSON5 in Dart: Common Questions

### Does `dart:convert` support JSON5?

No. `jsonDecode` parses strict JSON, so a comment, an unquoted key or a trailing comma is rejected. Use the `json5` package, or convert the file to JSON in your build.

### Does the package work on Flutter web?

pub.dev tags it for web and wasm, and its changelog notes web support was added in 0.5.2. The code is plain Dart with no platform libraries. We did not run it in a browser.

### How do I read a JSON5 file outside Flutter?

Read the text with `File(path).readAsStringSync()` from `dart:io` and pass it to `json5Decode`. The asset bundle is only for files packaged inside a Flutter app.

### Can I keep comments when I edit a file?

Not with `json5` 0.8.2: comments are dropped at parse time. `json5_plus` advertises a formatter that preserves them; test it on your files first.

### Is the package safe on untrusted input?

It builds plain maps and lists and never evaluates input. Dart has no prototype chain to pollute. Still cap the input size before parsing; see the [security guide](https://json5.dev/tutorials/security/).

### Why not just use JSONC?

Dart has a `jsonc` package whose pub.dev description is "JSON with comments and trailing commas", which names nothing beyond those two. If you need unquoted keys, single quotes or hex numbers, you need JSON5. The trade-offs are in [JSON5 vs JSONC](https://json5.dev/compare/jsonc/).

## Related Pages

[![Kotlin logo](https://json5.dev/images/tech/kotlin.png)

### Kotlin Guide

JSON5 on the JVM and Android

](https://json5.dev/kotlin/)[![Swift logo](https://json5.dev/images/tech/swift.svg)

### Swift Guide

The iOS side of a mobile app

](https://json5.dev/swift/)[![List icon](https://json5.dev/images/icons/list.png)

### All Implementations

Every language, side by side

](https://json5.dev/implementations/)

## Sources

(9)

1.  [pub.dev: json5 0.8.2](https://pub.dev/packages/json5) and its API at pub.dev/api/packages/json5 (versions, publisher, score)
2.  [damphat/json5-dart on GitHub](https://github.com/damphat/json5-dart), and the 0.8.2 source archive: README, CHANGELOG, `lib/` and `test/`
3.  [pub.dev: json5\_plus 0.2.1](https://pub.dev/packages/json5_plus) and its [README on GitHub](https://github.com/AndyKing42/json5_plus)
4.  [pub.dev: json5\_model 5.0.1](https://pub.dev/packages/json5_model)
5.  [pub.dev: jsonc 0.0.3](https://pub.dev/packages/jsonc)
6.  [pub.dev: json\_serializable 6.15.2](https://pub.dev/packages/json_serializable) and the [repository README](https://github.com/google/json_serializable.dart)
7.  [Flutter: JSON and serialization](https://docs.flutter.dev/data-and-backend/serialization/json)
8.  [Flutter: Adding assets and images](https://docs.flutter.dev/ui/assets/assets-and-images)
9.  [Dart stable channel VERSION file](https://storage.googleapis.com/dart-archive/channels/stable/release/latest/VERSION) (3.14.1, November 17, 2026)

Last reviewed: November 29, 2026.
