[英]how to json.stringify() a string
我有一個復雜的對象,它作為字符串存儲在文本文件中
這是我從文本文件中讀取的數據
[
{
name: "V",
number: 20,
coords: {
"cn": {
points: [
[23,32,32],
[32,32,32]
],
B: "VC",
label: "ds"
}
}
}]
我想將其轉換為 JSON 字符串
注意:- 我不能使用 eval 函數我已經嘗試過這個 JSON.stringify 但我得到了這個輸出:-
" [\r\n {\r\n name: \"V\",\r\n number: 20,\r\n coords: {\r\n \"cn\": { \r\n points: [\r\n [23,32,32],\r\n [32,32,32]\r\n ], \r\n B: \"VC\", \r\n label: \"ds\"\r\n }\r\n }\r\n }]"
您可以使用eval()
和JSON.stringify()
。 eval()
會將其轉換為有效的 JavaScript 對象,現在您可以使用JSON.stringify()
將其轉換為 JSON 字符串。
var str='[\\ {\\ name: "V",\\ number: 20,\\ coords: {\\ "cn": { \\ points: [\\ [23,32,32],\\ [32,32,32]\\ ], \\ B: "VC", \\ label: "ds"\\ }\\ }\\ }]'; document.write(JSON.stringify(eval(str)));
我不知道這是什么原因! 將 object-form-string 轉換為 JSON-string 但在您的情況下很容易:
let object_form_string = `[ { name: "V", number: 20, coords: { "cn": { points: [ [23,32,32], [32,32,32] ], B: "VC", label: "ds" } } }]` let json_form_string = object_form_string.replace(/(name|number|coords|points|B|label)(?=:)/g, "\\"$&\\"") let obj_json = JSON.parse(`{"coordination": ${json_form_string}}`) // add {} to change array to object // add "coordination" (just an example) to access to data // read/write data (optional of course) let json = JSON.stringify(obj_json) console.log(json) console.log(`type of obj_json is: ${typeof obj_json}`) console.log(json_form_string) console.log(`name is: ${obj_json.coordination[0].name}`) console.log(`number is: ${obj_json.coordination[0].number}`)
享受,不要使用 eval()
如果已將其存儲為字符串,那么它不是已經存在於JSON中嗎? 您無需再將其轉換。 這就是\\ r和\\ n出現的原因。 您無需再將其轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.