JSON.stringify:如何跳过一个(或多个)对象的缩进 [英] JSON.stringify: how to skip indentation for one (or more) objects

查看:58
本文介绍了JSON.stringify:如何跳过一个(或多个)对象的缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要为某些特定的子对象缩进所有对象除了.

I want to indent all the object except for some specific sub-objects.

这是我最接近解决此问题的方法.在示例中,我想避免缩进 color :

This is the closest I have gotten to solving the issue. In the example, I want to avoid indenting color:

let obj = {
    colorsPerValue: [
        { value: 0.0, color: { r: 240, g: 59, b: 32 } },
        { value: 0.5, color: { r: 255, g: 255, b: 255 } },
        { value: 1.0, color: { r: 44, g: 162, b: 95 } }
    ]
};
let str = JSON.stringify(obj, replacer, 2);
console.log(str);

replacer(name, val) {
    if (name === 'color') {
        return JSON.stringify(val); // stringify with no indentation
    } else {
        return val; // return as is
    }
};

所需结果:

{
    colorsPerValue: [
        { 
            value: 0.0, 
            color: { r: 240, g: 59, b: 32 } 
        },
        { 
            value: 0.5, 
            color: { r: 255, g: 255, b: 255 } 
        },
        { 
            value: 1.0, 
            color: { r: 44, g: 162, b: 95 } 
        }
    ]
}

实际结果(您猜对了,返回JSON.stringify(val); 返回一个序列化的 string ,这不是我想要的):

Actual result (you guessed it, return JSON.stringify(val); returns a serialized string which is not what I wanted):

{
  "colorsPerValue": [
    {
      "value": 0,
      "color": "{\"r\":240,\"g\":59,\"b\":32}"
    },
    {
      "value": 0.5,
      "color": "{\"r\":255,\"g\":255,\"b\":255}"
    },
    {
      "value": 1,
      "color": "{\"r\":44,\"g\":162,\"b\":95}"
    }
  ]
}

let obj = {
  colorsPerValue: [
    { value: 0.0, color: { r: 240, g: 59, b: 32   } },
    { value: 0.5, color: { r: 255, g: 255, b: 255 } },
    { value: 1.0, color: { r: 44, g: 162, b: 95   } }
  ]
};
let str = JSON.stringify(obj, replacer, 2);
console.log(str);

function replacer(name, val) {
  if (name === 'color') {
    return JSON.stringify(val); // stringify with no indentation
  } else {
    return val; // return as is
  }
};

推荐答案

您可以在以"color":开头的大括号中去除所有空白.

You could strip all whitespace in the curly brackets which starts with "color":.

var obj = {
        colorsPerValue: [
            { value: 0.0, color: { r: 240, g: 59, b: 32 } },
            { value: 0.5, color: { r: 255, g: 255, b: 255 } },
            { value: 1.0, color: { r: 44, g: 162, b: 95 } }
        ]
    },
    str = JSON
        .stringify(obj, null, 2)
        .replace(/("color": \{)([^}]+)/g, (_, a, b) => a + b.replace(/\s+/g, ' '));

console.log(str);

这篇关于JSON.stringify:如何跳过一个(或多个)对象的缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆