user2467545
user2467545

Reputation:

Validate JSON String

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.

Upvotes: 2

Views: 444

Answers (2)

Devy
Devy

Reputation: 10179

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 '.'

Upvotes: 0

Nidhish Krishnan
Nidhish Krishnan

Reputation: 20741

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;
}

Upvotes: 2

Related Questions