2

I am trying to make a JSON String but I am always getting an exception while validating the JSON String using any tool -

Below is my JSON String which I am not able to validate properly -

{"script":"#!/bin/bash hello=$jj1 echo $hello echo $jj1 echo $jj2 for el1 in $jj3 do echo \"$el1\" done for el2 in $jj4 do echo \"$el2\" done for i in $( ls ); do echo item: $i done"}

It is always giving me -

Invalid characters found.

What else I am supposed to escape?

Below is my shell script which I want to represent as JSON String -

#!/bin/bash

hello=$jj1

echo $hello

echo $jj1
echo $jj2

for el1 in $jj3
do
    echo "$el1"
done

for el2 in $jj4
do
    echo "$el2"
done

for i in $( ls ); do
    echo item: $i
done

How do I use jackson or other libraries to make the above a valid JSON String.

9
  • What library are you using? Commented Dec 28, 2013 at 5:05
  • That is another issue. I am not sure how to use jackson or other libraries to make this shell script as a valid JSON document.. So I decided to represent this shell script as a JSON String manually.. Updated the details in the question. Commented Dec 28, 2013 at 5:08
  • Ok then I misunderstood getting an exception while validating the JSON String using any tool. Which tool did you use? Commented Dec 28, 2013 at 5:09
  • I used JSON Formatter Commented Dec 28, 2013 at 5:10
  • Aahh.. Might be they have different window in that tool.. Earlier, it was showing not valid.. And I guess, I made some changes then again I tried validating it, so I guess somehow it showed me the previous window. Anyways.. Thanks for confirming that.. Apart from that, is there any possibility of generating a valid JSON String in Java if I have a shell script like that? Commented Dec 28, 2013 at 5:14

2 Answers 2

2

You can use the .mayBeJSON(String str) available in the JSONUtils library for validating JSON in java

or else

A wild idea for validating JSON, try parsing it and catch the exception:

public boolean isJSONValid(String test)
{
    boolean valid = false;
    try {
        new JSONObject(test);
        valid = true;
    }
    catch(JSONException ex) { 
        valid = false;
    }
    return valid;
}
Sign up to request clarification or add additional context in comments.

Comments

0

What you have there is indeed a valid JSON raw string. In shell terminal, you do need to use single quotes to quote it in order to satisfy command prompt escape sequence.

{"script":"#!/bin/bash hello=$jj1 echo $hello echo $jj1 echo $jj2 for el1 in $jj3 do echo \"$el1\" done for el2 in $jj4 do echo \"$el2\" done for i in $( ls ); do echo item: $i done"}

Like this:

$ echo '{"script":"#!/bin/bash hello=$jj1 echo $hello echo $jj1 echo $jj2 for el1 in $jj3 do echo \"$el1\" done for el2 in $jj4 do echo \"$el2\" done for i in $( ls ); do echo item: $i done"}' | jq '.'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.