亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在不使用 JSON.stringify 的情況下將數組轉換為有效的 JSON 字符串?

在不使用 JSON.stringify 的情況下將數組轉換為有效的 JSON 字符串?

慕容708150 2022-07-21 10:15:26
我正在嘗試編寫一個接受一些對象的函數,例如一個數字、一個字符串、一個列表或一個映射(鍵值對);并將該輸入的有效 JSON 表示形式作為字符串返回。我已經為簡單的數字和字符串輸入設置了其他 json 編碼器:Input => Output a number with value 123 => 123 (string)a string with value abc => "abc" (string)但我在轉換數組時遇到問題,例如 [1,"2",3]Input => Output 1,2,three array => [1,2,"three"] (string) 這是我當前的代碼:var my_json_encode = function(input) {  if(typeof(input) === "string"){      return '"'+input+'"'  }  if(typeof(input) === "number"){      return `${input}`  }  //This is causing my issue  if(Array.isArray(input)) {      console.log(input)  }我可以簡單地添加并返回 JSON.stringify(input) 來更改它,但我不想使用它。我知道我可以創建某種遞歸解決方案,因為我為數字和字符串設置了基本案例。我被阻止了,任何幫助將不勝感激編輯:所以答案部分提供了下面的解決方案!謝謝 :)
查看完整描述

2 回答

?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

對于數組,對項目采用遞歸方法。


const

    json_encode = (input) => {

        if (typeof input === "string") return `"${input}"`;

        if (typeof input === "number") return `${input}`;

        if (Array.isArray(input)) return `[${input.map(json_encode)}]`;

    };


console.log(json_encode([1, 'foo', [2, 3]]));

console.log(JSON.parse(json_encode([1, 'foo', [2, 3]])));


查看完整回答
反對 回復 2022-07-21
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

您已經擁有將標量值轉換為 json 值的函數。


因此,您可以為所有數組成員調用此函數(例如,使用https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/map)然后加入它(https://developer .mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/join)并將'['和']'添加到結果字符串


PS:這種方法也適用于您擁有數組數組的情況


實現示例:


var my_json_encode = function(input) {


   if(typeof(input) === "string"){

     return '"'+input+'"'

   }

   if(typeof(input) === "number"){

     return `${input}`

   }


   if(Array.isArray(input)) {

      const formatedArrayMembers = input.map(value => my_json_encode(value)).join(',');

      return `[${formatedArrayMembers}]`;

   }

}


查看完整回答
反對 回復 2022-07-21
  • 2 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號