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

如何将含转义符、换行符的字符串转为纯字符串并生成JSONObject

Solution to Convert Formatted JSON String to Compact JSON & JSONObject (No Regex)

Hey there! Let's work through this problem together. You want to turn that formatted, newline-filled string into a compact JSON string (and eventually a JSONObject) without using regex—totally doable. Here are two straightforward methods:

Method 1: Pure String Manipulation (No Regex)

Since your string contains literal \n characters (the newlines you see in output), we can use basic String.replace() (which replaces all literal matches, no regex needed) to clean things up:

String str = "[{\\n \"country_group\": [\"Asia\"],\\n \"country\": [\\n \"IND\" , \"China\"\\n ]\\n },\\n {\\n \"country_group\": [\"NAmerica\"],\\n \"country\": [\\n \"US\"\\n ]\\n }]";

// Step 1: Remove all newline characters
String compactStr = str.replace("\n", "");

// Step 2: Clean up extra consecutive spaces (since removing newlines might leave doubles)
while (compactStr.contains("  ")) {
    compactStr = compactStr.replace("  ", " ");
}

// Print the compact string (matches your desired output)
System.out.println(compactStr);

// Convert to JSONObject (note: your input is a JSON array, so we'll use JSONArray first)
JSONArray jsonArray = new JSONArray(compactStr);
// If you need a wrapping JSONObject:
JSONObject jsonObject = new JSONObject();
jsonObject.put("countryList", jsonArray);

Note: We use String.replace() (not replaceAll()) because it works with literal strings, not regular expressions—perfect for your requirement.

The best approach is to skip manual string cleaning entirely. JSON parsers (like org.json, Jackson, or Gson) automatically ignore whitespace (newlines, spaces, tabs) in valid JSON. This is more reliable because it avoids accidental damage to actual string content (e.g., if a country name had a newline in it, manual replacement would break it).

Using org.json as an example:

import org.json.JSONArray;
import org.json.JSONObject;

String str = "[{\\n \"country_group\": [\"Asia\"],\\n \"country\": [\\n \"IND\" , \"China\"\\n ]\\n },\\n {\\n \"country_group\": [\"NAmerica\"],\\n \"country\": [\\n \"US\"\\n ]\\n }]";

// Directly parse the original string into a JSONArray (since your input is an array)
JSONArray jsonArray = new JSONArray(str);

// To get the compact JSON string you want, just call toString()
System.out.println(jsonArray.toString());

// Convert to a JSONObject if needed (e.g., wrap the array in a key-value pair)
JSONObject jsonObject = new JSONObject();
jsonObject.put("countries", jsonArray);

This method is cleaner, safer, and still avoids regex entirely—win-win!

内容的提问来源于stack exchange,提问作者saurabh gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:42:37