Home  >  Article  >  Backend Development  >  How to remove unwanted characters between keys and values ​​in JSON?

How to remove unwanted characters between keys and values ​​in JSON?

WBOY
WBOYforward
2024-02-09 17:15:071042browse

How to remove unwanted characters between keys and values ​​in JSON?

php editor Strawberry is here to share with you a tip about JSON processing: How to delete unnecessary characters between keys and values ​​in JSON? When processing JSON data, we often need to clean up some useless characters to improve the readability of the data and reduce the size of data transmission. By using PHP's related functions and regular expressions, we can easily remove unnecessary characters between keys and values ​​in JSON, making the data more tidy and standardized. Next, I will introduce the specific operation steps and code implementation in detail.

Question content

I have this JSON: {"key1": "value1", \n \n "key2": "value2\nwithnewline"}

I want:

  1. Delete\n\n
  2. Retain value2\n and newline characters.

So I will have a valid JSON.

I tried :regex but couldn't figure out how to specify outside of keys and values.

and this:

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())
}

Go playground link: https://go.dev/play/p/zvNSCuE4SjQ

This doesn't work as it could \n Actually it does \ n

Workaround

Given the parameters of your question, you can use strings.ReplaceAll to replace all\n\n:

cleaned := strings.ReplaceAll(input, "\\n \\n ", "")

If you want to continue using the current strategy, you will encounter some problems. One of them is that regardless of your condition, you always write the string: cleaned.WriteByte(jsonStr[i]) happens in your if and else cases.

The above is the detailed content of How to remove unwanted characters between keys and values ​​in JSON?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete