Home » Java » Editing JSON file using Java ,where file is at remote location: SSH available

Editing JSON file using Java ,where file is at remote location: SSH available

Posted by: admin July 12, 2018 Leave a comment

Questions:

I have a JSON file in my linux box (remote). I am using org.json.simple.* library. I would like to just update one of the attributes and write it back. In JSON file, I know there is one key with “XXXX” and its value is “YYYY”. I want to update its value to “WWWWXYZ”.

Below is code snippet on what is done so far

Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;

InputStream stream = sftp.get(<JSON FILE LOCATION>);
try {
    JSONParser jsonParser = new JSONParser();

    try {

        JSONObject jsonObject = (JSONObject)jsonParser.parse(
            new InputStreamReader(stream, "UTF-8")
        );

        System.out.println(jsonObject.toJSONString());

        jsonObject.put("XXXX", "WWWWXYZ");
        System.out.println(jsonObject.toJSONString());

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

If you see, I was able to get the JSON file using SSH and then converted that to JSON Object, edited the JSON object. Now I would like to write back it to the actual file in linux box. Please help on how to write back my JSONObject to file, which is located at remote location (my linux box).

Answers: