javascript - 使用 JSON.stringify() 在每个键、值后添加换行符

标签 javascript json

我想使用 JSON.stringify() 在对象中的每个键值对之后添加换行符

在我的实际代码中,我将获得很多键值对,并且新行使其更易于阅读。

示例代码是:

let test = {'key' : ['one', 'two', 'three'], 'keyTwo' : ['one', 'two', 'three']}

let testOne = JSON.stringify(test, null, '\t')

console.log(testOne)

输出:

{
        "key": [
                "one",
                "two",
                "three"
        ],
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}

我想要:

{
        "key": [
                "one",
                "two",
                "three"
        ],
                                   // <----- newline here
        "keyTwo": [
                "one",
                "two",
                "three"
        ]
}

我已经尝试过

let test = {'key' : ['one', 'two', 'three'] + "\\n", 'keyTwo' : ['one', 'two', 'three']+ "\\n"}

let testOne = JSON.stringify(test, null, '\t\n')

都不起作用

最佳答案

const test = {'key' : ['one', 'two', 'three'], 'keyTwo' : ['one', 'two', 'three'], 'keyThree' : ['one', 'two', 'three']}

const testOne = JSON
    .stringify(test, null, "\t")
    .replaceAll(
        "],\n\t\"", 
        "],\n\n\t\""
    );
console.log(testOne);

关于javascript - 使用 JSON.stringify() 在每个键、值后添加换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71091649/

相关文章:

javascript - React Router Link 不适用于 LeafletJS

javascript - 为目标 div 设置默认内容

php - 在Windows 7命令行窗口中通过PHP套接字发送JSON数据

arrays - Swift 解析 JSON 响应

java - 如何使用从 Spring MVC 发回的 JSON 对象填充 jQuery 数据表的行?

javascript - 从 ng-click 调用动态函数

javascript - POST 请求在 Android 9 (JAVASCRIPT/CORDOVA/PHONEGAP ) 中返回错误

ios - 无法将类型 '__NSDictionaryM' (0x1055952b0) 的值转换为 'NSString' (0x1023e3c60)

java - 如何从嵌套的json中获取键的所有值

javascript - 掌握 JS Promise