PrismarineJS / node-mojangson

A mojangson parser written in node.js
17 stars 9 forks source link

Incorrect escape string serialization #30

Closed ShirasawaSama closed 3 years ago

ShirasawaSama commented 3 years ago
const origin = '"'
const str = JSON.stringify(origin)
const str2 = MojangSON.parse(MojangSON.stringify({ str })).str

console.log(str === str2) // false
console.log(origin === JSON.parse(str)) // true
console.log(str) // "\""
console.log(str2) // """

And this works:

const escapeJSON = text => text.replace(/"/g, '\\u0022').replace(/'/g, '\\u0027')

const str = JSON.stringify(escapeJSON(origin))
const str2 = MojangSON.parse(MojangSON.stringify({ str })).str
rom1504 commented 3 years ago

Why are you comparing what's returned by parse and stringify ? Those are 2 different things

ShirasawaSama commented 3 years ago

@rom1504 I stringify an item NBT with a double quoted name { DisplayName: '"' } and tried to parse it. I found that it could not be parsed.

console.log(JSON.parse(parse(stringify({ DisplayName: JSON.stringify('"') })).DisplayName))
rom1504 commented 3 years ago

What do you actually want to do ? Is there any error ?

ShirasawaSama commented 3 years ago

@rom1504 I need parse an item from NBT, modify its display name, and stringify it.

However, when I parse the serialized data again, the DisplayName string obtained is inconsistent with the expected one.

I expected "\"", but I got """.

rom1504 commented 3 years ago

Can you try not using json parse and json stringify ? And posting the code that does what you want to do

rom1504 commented 3 years ago

The \ should only appear in stringified form, not parsed

ShirasawaSama commented 3 years ago
const str1 = '"\\""'
const str2 = parse(stringify({ str1 })).str1
console.log(str1 === str2) // false
ShirasawaSama commented 3 years ago

Sorry, it's my problem