JSON to Javascript Object Converter

Paste JSON and get a JavaScript object literal. A key loses its quotes when it is a valid identifier and keeps them when it is not, so firstName comes out bare and first-name stays quoted. Use it to turn an API response into a mock, a fixture or a component's initial state.

Input JSON
JS Output

1 JSON to JavaScript example

Input JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[
    {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com",
        "roles": [
            "admin",
            "editor"
        ],
        "active": true
    },
    {
        "id": 2,
        "name": "Jane Smith",
        "email": "jane@example.com",
        "roles": [
            "user"
        ],
        "active": false
    }
]

JS Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const users = [
    {
        id: 1,
        name: 'John Doe',
        email: 'john@example.com',
        roles: [
            'admin',
            'editor'
        ],
        active: true
    },
    {
        id: 2,
        name: 'Jane Smith',
        email: 'jane@example.com',
        roles: [
            'user'
        ],
        active: false
    }
];

2 What JSON to JavaScript is for

Mocks and fixtures

Paste a real response, copy the object literal and assign it in a test file. The test then runs without a network call.

Initial state

The starting value for a React or Vue component, already in the shape the API returns.

Config modules

Move a JSON config into a module when you need comments. A .js file can export the object, explain a setting and compute a value, and JSON allows none of those.

How to use the JSON to JavaScript tool

  1. Paste JSON into the left editor. Upload JSON reads a file from disk, and Load URL fetches from an endpoint, provided it allows cross-origin requests.
  2. The JavaScript object literal appears on the right as you type. Keys that are valid identifiers lose their quotes; others stay quoted.
  3. Bad input shows Invalid JSON, or the line number that failed, next to the editor label. Fix that line and the output refreshes by itself.
  4. Click Beautify input to reindent the JSON on the left if it arrived as one long line.
  5. Click Copy Result and paste the literal after const data = or export default in your module.

How to convert JSON to a JavaScript object literal in Node.js and Python

JavaScript (Node.js)

const util = require("node:util");

const raw = '{"id":1,"first-name":"Ada","tags":["a","b"],"meta":{"active":true}}';
const data = JSON.parse(raw);

const literal = util.inspect(data, {
  depth: null,
  compact: false,
  maxArrayLength: null,
  maxStringLength: null,
});

console.log("export default " + literal + ";");

util.inspect prints valid JavaScript for plain data. The maxArrayLength and maxStringLength options stop it truncating with "... more items".

Python

import json, re

raw = '{"id":1,"first-name":"Ada","tags":["a","b"],"meta":{"active":true}}'
text = json.dumps(json.loads(raw), indent=2)

# Drop quotes around keys that are valid JS identifiers
literal = re.sub(r'^(\s*)"([A-Za-z_$][\w$]*)":', r'\1\2:', text, flags=re.M)

print("export default " + literal + ";")

The regex only touches lines that start with a key, so string values containing a colon are left alone.

Common errors and how to fix them

SyntaxError: Unexpected token ':' when running the file
A bare object literal at statement position is parsed as a block. Assign it: const data = { ... }; or wrap it in parentheses.
Property names such as first-name or 2fa cause a SyntaxError
Those are not valid identifiers, so they must stay quoted. The tool keeps the quotes; if you removed them by hand, put them back.
The literal contains \u00e9 instead of é
The JSON escaped its Unicode. Both spellings are the same string to JavaScript, so you can leave it. If you prefer the plain character, JSON.parse followed by JSON.stringify writes it out as é.
ESLint complains about quote-props or quotes
The project style differs from the output (for example single quotes). Run the file through Prettier or eslint --fix after pasting.

Good to know

Every JSON document is a valid JavaScript expression, so this conversion is cosmetic: quotes come off the keys and the values stay the same. In the Node snippet, util.inspect also switches strings to single quotes. There was one historical exception, the U+2028 and U+2029 line separator characters, which JSON allowed inside strings and older JavaScript engines rejected. ES2019 fixed that.

Check whether you need this at all. Bundlers import .json files directly, and so does Node with the import attribute { type: "json" }. Convert to a .js module when you want comments in the data, computed values or a TypeScript type on the export.

Specifications and references

This tool follows the specifications below. Read them when you need the exact normative wording, for example to settle an edge case between two implementations.

Guides and tutorials

Frequently Asked Questions

What is the difference between JSON and a JavaScript object?

JSON is a strict text format: keys must be double-quoted, and it allows no trailing commas, comments, functions or undefined. A JavaScript object literal is looser and lives in code. This tool rewrites the JSON as an object literal and removes the quotes from keys wherever the language allows it.

Can this convert functions?

No. JSON cannot contain functions, so there is nothing to convert. The tool handles data only: objects, arrays, strings, numbers, booleans and null.

Is the output ES6 compatible?

Yes. Object literal notation has been valid since the first version of JavaScript, so the output works in ES modules, CommonJS, Node.js and TypeScript.

When are keys left quoted?

A key that is not a valid identifier keeps its quotes, for example one that contains a space or a hyphen, or one that starts with a digit. Valid identifiers such as userId lose their quotes.

Why would I need this instead of JSON.parse()?

Use JSON.parse() for data that arrives at runtime. This tool is for source code: a default config object, mock data in tests, a fixtures file or a Storybook story, where a readable literal is easier to work with than a JSON string.

Related

JSON to PHP array does the same job for backend code. CSV to JavaScript starts from a spreadsheet, and the JSON formatter shows where input that will not parse goes wrong.

More Data Converters

Browse all data converters

Copied to clipboard!