How to replace a string inside of Json using java
I think a simple loop should solve your problem:
public static void main(String[] args) throws JSONException {
JSONArray array = new JSONArray("[" +
" {" +
" originalName : \"Case #\"," +
" modifiedLabel : \"Case #\"," +
" labelId : \"case_number_lbl\"," +
" isEditable : \"true\"," +
" imageClass : \"\"" +
" }" +
"]");
System.out.println(array.toString(2));
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
JSONArray keys = object.names();
for (int j = 0; j < keys.length(); j++) {
String key = keys.getString(j);
if (object.getString(key).equals("Case #")) {
object.put(key, "Ticket #");
}
}
}
System.out.println();
System.out.println(array.toString(2));
}
replace substring from string in java
public static void main(String...strings) {
String inputString = "{\n" + "\"id\": 1,\n" + "\"data\":[\n" + "{\n" + "\"to\":123456789,\"name\":\"james\",\"value\":200\n" + "},\n" + "{\n" + "\"to\":123456789,\"name\":\"jhon\",\"value\":20\n" + "}]\n" + "}\n" + "";
Pattern pattern = Pattern.compile("(?:\"name\":\")(.*?)(?:\"value\":)[0-9]*");
Matcher m = pattern.matcher(inputString);
while (m.find()) {
String[] matches = m.group().split(",");
String name = null, value = null;
for (String match : matches) {
if(match.contains("name")){
name= match.substring(match.indexOf("name")+"name".length()).replaceAll("\"", "");
}else if(match.contains("value")) {
value= match.substring(match.indexOf("value")+"value".length()).replaceAll("\"", "");
}
}
System.out.println("Bonjour Mr. "+name+" votre score est value "+value);
}
}
Replace a String with specific list of strings in java
List is declared asList<String> varList = Arrays.asList("VAR_TEMP", "VAR_TEMPA", "VAR_TEMPB");
Operation is String operation = "var temp = VAR_TEMPB";
The loop acts as following:
- Does operation (var temp = VAR_TEMPB) contains VAR_TEMP? Yes
- Now operation now is var temp = 'HI'B
- Does operation (var temp = 'HI'B) contains VAR_TEMPA? No. Operation is not changed
- Does operation (var temp = 'HI'B) contains VAR_TEMPB? No. Operation is not changed
A simple solution should be the use of Regular Expression, when you express the exact matching pattern. For example:
class Scratch {
public static void main(String[] args) {
final List<Pattern> varList =
Arrays.asList(
Pattern.compile("(VAR_TEMP)$"),
Pattern.compile("(VAR_TEMPA)$"),
Pattern.compile("(VAR_TEMPB)$"));
String operation = "var temp = VAR_TEMPB";
Matcher tmp;
for (Pattern item : varList) {
tmp = item.matcher(operation);
operation = tmp.find() ? operation.replace(tmp.group(), "'HI'") : operation;
}
System.out.println("Final operation : " + operation);
}
}
Within a JSON string how does one for all string values of a given key replace any occurrence of a specific substring?
I wont recommend using replace
on a json converted to string.
Instead, I'd recursively loop through the array/objects and alter the value if needed
Simple example:
const data = [{"name": "please, I said please", "title": "Test One", "more": [{"name": "another name", "title": "please write something"} ] }, {"name": "testTwo", "title": "Test Two"}, {"name": "testThree", "title": "Test Three"}, {"name": "testFour", "title": "Test Four"} ];
const regx = new RegExp(`\\bplease\\b`, 'gi');
function replace(obj) {
for (var k in obj) {
if (typeof obj[k] == "object" && obj[k] !== null) {
replace(obj[k]);
} else if (k === 'title') {
obj[k] = obj[k].replaceAll(regx, 'could you');
}
}
return obj;
}
const result = data.map(o => replace(o));
console.log(result);
Replace a + with a space in a string
Whether your conversion makes sense or not, you may convert your result with this:
const replace = {type: "MERCEDES+BENZ"}
const replacedReplace = JSON.parse(JSON.stringify(replace).replace('+', ' '))
console.log(replacedReplace)
Related Topics
How to Trim White Space from All Elements in Array
Java Socket Api: How to Tell If a Connection Has Been Closed
Field Required a Bean Which Could Not Be Found in Springboot
Jackson @Jsonproperty Not Working If Property Name Not Equal Field Name
Spring Boot/Spring Kafka Ssl Configuration by Environment Variables Impossible
Finding Max Value in an Array Using Recursion
Java Execution Pops a New Window and Immediately Disappears
Return Json Object from a Spring-Boot Rest Controller
Java Package Does Not Exist Error
How to Move Marker Along Polyline Using Google Map
Why Is My Spring @Autowired Field Null
Spring Junit: How to Mock Autowired Component in Autowired Component
Checking If a String Contains Only Digits (Isdigitmethod Required)
Spring Boot JPA Unknown Column in Field List
String.Replaceall Single Backslashes With Double Backslashes
Java How to Set an Auto Increment Attribute
How to Test for Blank Line With Java Scanner
Calculate the Number of Items Displayed by Recyclerview and Place in a Textview