You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除JSON键值对之间的多余无效换行字符?

问题描述

我有如下JSON字符串:

{"key1": "value1", \n \n "key2": "value2\nwithnewline"}

需求是:

  • 删除键值对外部的\n \n
  • 保留value2\nwithnewline里的\n
    最终得到有效的JSON格式。

我试过正则表达式,但没法只匹配键值对外部的内容;还写了一段Go代码:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    jsonStr := `{"key1": "value1", \n \n "key2": "value2\nwithnewline"}`
    var cleaned bytes.Buffer
    quoteCount := 0

    for i := 0; i < len(jsonStr); i++ {
        if jsonStr[i] == '"' {
            quoteCount++
        }

        if quoteCount%2 == 0 && jsonStr[i] != '\n' {
            cleaned.WriteByte(jsonStr[i])
        } else if quoteCount%2 == 1 {
            cleaned.WriteByte(jsonStr[i])
        }
    }

    fmt.Println(cleaned.String())
}

这段代码无效,因为字符串里的\n实际是由\和n两个单独的字符组成的,不是转义后的换行符。

解决方案

修正后的Go代码可以正确识别引号内外的\n字符组合,只删除外部的:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    jsonStr := `{"key1": "value1", \n \n "key2": "value2\nwithnewline"}`
    var cleaned bytes.Buffer
    inQuotes := false
    escaped := false

    for i := 0; i < len(jsonStr); i++ {
        c := jsonStr[i]
        // 处理转义字符
        if c == '\\' && !escaped {
            escaped = true
            cleaned.WriteByte(c)
            continue
        }
        // 处理引号:非转义引号切换引号内状态
        if c == '"' && !escaped {
            inQuotes = !inQuotes
            cleaned.WriteByte(c)
            escaped = false
            continue
        }
        // 处理引号外的\n组合:跳过这两个字符
        if !inQuotes && c == '\\' && i+1 < len(jsonStr) && jsonStr[i+1] == 'n' {
            i++
            escaped = false
            continue
        }
        // 其他字符直接写入
        cleaned.WriteByte(c)
        escaped = false
    }

    fmt.Println(cleaned.String())
}

这段代码的核心逻辑:

  • 用inQuotes标记是否处于JSON字符串值内部
  • 用escaped处理转义字符(比如\"这类转义引号,不会误判引号状态)
  • 仅当不在引号内时,跳过\+n的组合
  • 引号内的所有字符(包括\n)全部保留

运行后输出的有效JSON:

{"key1": "value1",  "key2": "value2\nwithnewline"}

内容的提问来源于stack exchange,提问作者Jill Clover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:57:21