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

WBOY
Release: 2024-02-09 17:15:07
forward
1059 people have browsed it

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())
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!