簡體   English   中英

使用 JSON.stringify 時如何在列表元素之間添加空格?

[英]How do I add spaces between list elements when using JSON.stringify?

我正在使用 Javascript 的JSON.stringify() function 將字符串列表轉換為以逗號分隔的 JSON object。

 array = ["a", "b", "c"]; console.log(JSON.stringify(array)); // Output: ["a","b","c"]

我想在列表元素之間添加一個空格。 我嘗試使用space參數,但這會向我的 output 添加額外的換行符。

 array = ["a", "b", "c"]; console.log(JSON.stringify(array, null, " ")); // Desired output: // ["a", "b", "c"] // // Actual output: // [ // "a", // "b", // "c" // ]

關於在對象之間添加空格有一個類似的問題 JSON.stringify 但是,最佳答案建議通過大括號拆分元素並重新加入,而列表元素不以大括號分隔。

output JSON 使用JSON.stringify時如何列出用空格分隔的元素?

類似於@mykaf 的回答,但不會更改由於字符 escaping 而包含逗號的字符串內容。

const array = ["string without commas", "string,with,commas"];
const myJSON = JSON.stringify(array).replaceAll(',"', ', "');
// '["string without commas", "string,with,commas"]'

只知道這僅在您的數組被字符串化時才重要。 一旦反序列化回 object,元素之間就沒有逗號,因為該概念僅存在於字符串中,而不存在於 JSON 對象/數組中。

您可以使用replace來刪除新行。

 array = ["a", "b", "c"]; console.log(JSON.stringify(array, null, 1).replace(/\n/g, ''));

由於列表項由逗號分隔,似乎用逗號和空格替換逗號應該可以解決問題:

var myJSON = JSON.stringify(array).replaceAll(',', ', ');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM