Skip to content

Commit

Permalink
Quote numeric keys for json-stringify parser (prettier#14083)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker authored and medikoo committed Jan 4, 2024
1 parent 3bd3347 commit fbe4d87
Show file tree
Hide file tree
Showing 4 changed files with 356 additions and 91 deletions.
17 changes: 17 additions & 0 deletions changelog_unreleased/json/14083.md
@@ -0,0 +1,17 @@
#### Quote numeric keys for json-stringify parser (#14083 by @fisker)

<!-- prettier-ignore -->
```jsx
// Input
{0: 'value'}

// Prettier stable
{
0: "value"
}

// Prettier main
{
"0": "value"
}
```
29 changes: 19 additions & 10 deletions src/language-js/printer-estree-json.js
Expand Up @@ -48,15 +48,13 @@ function genericPrint(path, options, print) {
case "BooleanLiteral":
return node.value ? "true" : "false";
case "StringLiteral":
case "NumericLiteral":
return JSON.stringify(node.value);
case "Identifier": {
const parent = path.getParentNode();
if (parent && parent.type === "ObjectProperty" && parent.key === node) {
return JSON.stringify(node.name);
}
return node.name;
}
case "NumericLiteral":
return isObjectKey(path)
? JSON.stringify(String(node.value))
: JSON.stringify(node.value);
case "Identifier":
return isObjectKey(path) ? JSON.stringify(node.name) : node.name;
case "TemplateLiteral":
// There is only one `TemplateElement`
return print(["quasis", 0]);
Expand All @@ -68,6 +66,12 @@ function genericPrint(path, options, print) {
}
}

function isObjectKey(path) {
return (
path.getName() === "key" && path.getParentNode().type === "ObjectProperty"
);
}

const ignoredProperties = new Set([
"start",
"end",
Expand All @@ -85,8 +89,13 @@ const ignoredProperties = new Set([
function clean(node, newNode /*, parent*/) {
const { type } = node;
// We print quoted key
if (type === "ObjectProperty" && node.key.type === "Identifier") {
newNode.key = { type: "StringLiteral", value: node.key.name };
if (type === "ObjectProperty") {
const { key } = node;
if (key.type === "Identifier") {
newNode.key = { type: "StringLiteral", value: key.name };
} else if (key.type === "NumericLiteral") {
newNode.key = { type: "StringLiteral", value: String(key.value) };
}
return;
}
if (type === "UnaryExpression" && node.operator === "+") {
Expand Down

0 comments on commit fbe4d87

Please sign in to comment.