How to Modify Values in a JSON File Using XPath or JsonPath in Java

Question

How can I change values in a JSON file using XPath or JsonPath in Java?

import com.jayway.jsonpath.JsonPath;
import org.json.JSONObject;

public class JsonModifier {
    public static void main(String[] args) {
        String jsonString = "{ 'store': { 'book': [ { 'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95 }, { 'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 12.99 } ], 'bicycle': { 'color': 'red', 'price': 19.95 } } }";
        JSONObject jsonObject = new JSONObject(jsonString);
        System.out.println("Original JSON: " + jsonObject.toString());
        // Update the price of the bicycle
        JsonPath.parse(jsonObject.toString()).set("$.store.bicycle.price", 24.99);
        System.out.println("Updated JSON: " + jsonObject.toString());
    }
}

Answer

In Java, manipulating JSON data can be efficiently done using libraries like JsonPath, which allows you to query and update JSON objects easily. XPath is generally used for XML, while JsonPath serves a similar function for JSON.

import com.jayway.jsonpath.JsonPath;
import org.json.JSONObject;

// Example function to update JSON
public static void updateJSONValue(String jsonString, String jsonPath, Object newValue) {
    JSONObject jsonObject = new JSONObject(jsonString);
    JsonPath.parse(jsonObject.toString()).set(jsonPath, newValue);
    System.out.println("Updated JSON: " + jsonObject.toString());
}

Causes

  • Need to dynamically modify JSON data based on application logic.
  • Updating configurations that are stored in a JSON file.
  • Correcting errors in existing JSON data.

Solutions

  • Use the JsonPath library to query and update specific fields within the JSON structure.
  • Load the JSON data into a suitable object structure that allows manipulation before saving it back to a file.

Common Mistakes

Mistake: Not properly formatting the JSON string before processing.

Solution: Ensure the JSON string is valid before attempting to manipulate it using JsonPath.

Mistake: Using incorrect JsonPath syntax.

Solution: Refer to the JsonPath documentation to ensure your syntax matches the structure of your JSON data.

Helpers

  • JSON manipulation in Java
  • JsonPath usage in Java
  • Updating JSON values Java
  • How to use JsonPath
  • Java JSON example

Related Questions

⦿Understanding the Difference Between CLASSPATH and java.ext.dirs in Java

Explore the differences between CLASSPATH and java.ext.dirs in Java their purposes and best practices for configuration.

⦿How to Convert an Object Array of Booleans to a Primitive Boolean Array Using Streams in Java

Learn how to efficiently convert an Object array of booleans to a primitive boolean array using Java Streams in this detailed guide.

⦿Understanding JVM Instruction ALOAD_0 in the 'main' Method and Its Reference to 'args'

Learn why JVM instruction ALOAD0 in the main method references args instead of this with detailed explanations and code examples.

⦿How to Resolve 'No Query Registered for [query]' Error in Elasticsearch

Learn how to troubleshoot the No Query Registered for query error in Elasticsearch with stepbystep guidance and solutions.

⦿How Does Android's WebView AddJavascriptInterface Work?

Learn how to effectively use Androids WebView addJavascriptInterface to enhance web interactions in your apps.

⦿How to Add a Common Header to All Requests in Retrofit

Learn how to define a common header for all requests in Retrofit improving API authorization and request management.

⦿How to Fix Elasticsearch Painless Script Errors?

Learn how to troubleshoot and resolve undefined errors in Elasticsearch Painless scripts with our expert guide.

⦿How to Resolve Spring Boot Application Without a Main Class Error

Learn how to fix the no main class error in Spring Boot applications with detailed solutions and troubleshooting tips.

⦿How to Monitor Class Loading and Unloading Events in the JVM

Learn how to track class loading and unloading events in the Java Virtual Machine JVM with expert tips and code examples.

⦿How to Intercept Method Calls in Programming?

Learn how to intercept method calls in programming including techniques examples and common mistakes to avoid.

© Copyright 2025 - CodingTechRoom.com