Skip to content

Commit

Permalink
Fix NbtCompound.toPrettyString not quoting keys when necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
misode committed Oct 4, 2024
1 parent 36dfb49 commit f0423df
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/nbt/tags/NbtCompound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,12 @@ export class NbtCompound extends NbtTag {
if (this.size === 0) return '{}'
const i = indent.repeat(depth)
const ii = indent.repeat(depth + 1)
return '{\n' + Object.values(this.map((key, value) => {
return [key, ii + key + ': ' + value.toPrettyString(indent, depth + 1)]
})).join(',\n') + '\n' + i + '}'
const pairs = []
for (const [key, tag] of this.properties.entries()) {
const needsQuotes = key.split('').some(c => !StringReader.isAllowedInUnquotedString(c))
pairs.push((needsQuotes ? JSON.stringify(key) : key) + ': ' + tag.toPrettyString(indent, depth + 1))
}
return '{\n' + pairs.map(p => ii + p).join(',\n') + '\n' + i + '}'
}

public override toSimplifiedJson() {
Expand Down
16 changes: 16 additions & 0 deletions test/nbt/tags/NbtCompound.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,20 @@ describe('NbtCompound', () => {
const string = compound.toString()
expect(string).toEqual('{"hello \\"world\\"":4b}')
})

it('toPrettyString (key escaping)', () => {
const compound = new NbtCompound()
.set('hello "world"', new NbtByte(4))
const string = compound.toPrettyString()
expect(string).toEqual('{\n "hello \\"world\\"": 4b\n}')
})

it('toPrettyString (nested and quoted keys)', () => {
const compound = new NbtCompound()
.set('wrapper', new NbtCompound()
.set('first', new NbtByte(3))
.set('second key', new NbtString('hello world')))
const string = compound.toPrettyString()
expect(string).toEqual('{\n wrapper: {\n first: 3b,\n "second key": "hello world"\n }\n}')
})
})

0 comments on commit f0423df

Please sign in to comment.