JSON.parse解析错误?

时间:2020-05-07 07:48:43

标签: javascript json

我已经使用以下文本作为JSON.parse()的输入

let inputTxt = `{"result":[{"aliasName":null,"name":"SRDD","sort":0,"id":319488404634063872,"parentId":319472086895578112,"level":2},{"aliasName":null,"name":"Noodles","sort":11,"id":350368638463726592,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Sushi","sort":21,"id":350368638463726593,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Drink","sort":31,"id":350368638463726594,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Set","sort":41,"id":350368739890458624,"parentId":350368638434366464,"level":2},{"aliasName":"默认","name":"默认","sort":1,"id":319472086895578112,"parentId":null,"level":1},{"aliasName":null,"name":"Tendongo","sort":0,"id":350368638434366464,"parentId":null,"level":1}],"code":0,"message":"success[OK]","messageUuid":"437fcce5209d4d17b558403d4a8b859c","apiMessage":null}`

console.log(JSON.parse(inputTxt))

在这里您可以看到输出中类别的ID不同。

1 个答案:

答案 0 :(得分:-1)

问题很多。解析JSON时。它试图容纳大量的人。

最大值可以看成是:

Number.MAX_SAFE_INTEGER // (253 - 1) => 9007199254740991

更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

const str = "319488404634063872"
console.log(Number(str)) // 319488404634063900

// OR
const num  = 319488404634063872

console.log(num) // 319488404634063900

在解析convert it to string之前,可以使用replace函数作为解决方法。

let inputTxt = `{"result":[{"aliasName":null,"name":"SRDD","sort":0,"id":319488404634063872,"parentId":319472086895578112,"level":2},{"aliasName":null,"name":"Noodles","sort":11,"id":350368638463726592,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Sushi","sort":21,"id":350368638463726593,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Drink","sort":31,"id":350368638463726594,"parentId":350368638434366464,"level":2},{"aliasName":null,"name":"Set","sort":41,"id":350368739890458624,"parentId":350368638434366464,"level":2},{"aliasName":"默认","name":"默认","sort":1,"id":319472086895578112,"parentId":null,"level":1},{"aliasName":null,"name":"Tendongo","sort":0,"id":350368638434366464,"parentId":null,"level":1}],"code":0,"message":"success[OK]","messageUuid":"437fcce5209d4d17b558403d4a8b859c","apiMessage":null}`;

const format = (json) => json.replace(/\"id\":(\d+)/g, `"id":"$1"`)

console.log(JSON.parse(format(inputTxt)))