GuzzleHttp\Client JSON Return as String - laravel

I have very simple question, how to convert this strings to JSON ?
This string i am getting from Guzzle POST Request and here is code :
return $body->getBody()->getContents();
Result:
""k\n\n{\"success\":true,\"payload\":{\"id\":\"txn_ngS2aS9FY7raxy8JTUivAZCtWJy7EeznwPE8\"}}""
with var_dump result and what is that k before ?
string(79) "k {"success":true,"payload":{"id":"txn_eeM6T6Fvkq3Pr4AWtK2TKYmNwKmodNwVqJod"}}"

The string is already json_encoded, you should simply return the $body->getBody()->getContents().

I found problem isn't in my code but it was in external api payload, payload sending json data with "k" string.
Thanks #Ozan Kurt to figure out external link.
So right now only picking curly brackets with regex :
$result = preg_match("/{.+}", $body->getBody()->getContents(), $matched);
if ($matched) {
return json_decode($matched[0]);
}

Related

How to make Get Request with Request param in Postman

I have created an endpoint that accepts a string in its request param
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression") String expression) {
System.out.println(expression);
// code to validate the input string
}
While sending the request from postman as
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606/Curr_month:Y07608
// lets say this is a valid input
console displays as
Y07607=Curr_month:Y07606/Curr_month:Y07608 Valid
But when i send
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606+Curr_month:Y07608
//which is also an valid input
console displays as
Y07607=Curr_month:Y07606 Curr_month:Y07608 Invalid
I am not understanding why "+" is not accepted as parameter.
"+" just vanishes till it reaches the api! Why?
I suggest to add this regular expression to your code to handle '+' char :
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression:.+") String expression) {
System.out.println(expression);
// code to validate the input string
}
I didn't find any solution but the reason is because + is a special character in a URL escape for spaces. Thats why it is replacing + with a " " i.e. a space.
So apparently I have to encode it from my front-end
Its wise to encode special characters in a URL. Characters like \ or :, etc.
For + the format or value is %2. You can read more about URL encoding here. This is actually the preferred method because these special characters can sometimes cause unintended events to occur, like / or = which can mean something else in the URL.
And you need not worry about manually decoding it in the backend or server because it is automatically decoded, in most cases and frameworks. In your case, I assume you are using Spring Boot, so you don't need to worry about decoding.

How to avoid #RequestParam concatenating when a "+" operator is recieved as parameter?

I'm new to Spring Framework and I'm trying to build this simple calculator app.
I've got this #RestController with this method:
#RequestMapping(value = "/calculate", method = RequestMethod.GET)
public String calculate(#RequestParam(value = "a") String a, #RequestParam(value = "b") String b, #RequestParam(value = "operator") String operator) {
//System.out.println(operator);
if(operator.equals("+")){
return String.valueOf((Integer.valueOf(a) + Integer.valueOf(b)));
}
if(operator.equals("-")){
return String.valueOf((Integer.valueOf(a) - Integer.valueOf(b)));
}
if(operator.equals("*")){
return String.valueOf((Integer.valueOf(a) * Integer.valueOf(b)));
}
if(operator.equals("/")){
return String.valueOf((Integer.valueOf(a) / Integer.valueOf(b)));
}
Ok, the problem here is that when I send a "+" parameter to sum the two variables the program is concatenating both int's instead of performing the sum.
The rest of the operations are working fine, except for the sum. I've tried sending a "/+" without luck.
Any idea how this can be solved and most importantly, why is this happening ?
Thanks a lot :D
You should be aware of that + is a special character. To use + as a value you need to encode it as %2B in your GET request.
For example:
http://localhost:8080/calculate?a=3&b=5&operator=%2B

How can I use queryBuilders.wrapperQuery base64 encoded string

I have a json string to build a query, and I need to convert this to QueryBuilder. (ES Ver. 6.3.0)
I found that I can use wrapperQuery method, so I wrote this code:
String str = cond.getFilter().toString();
QueryBuilder filter = QueryBuilders.boolQuery().must(QueryBuilders.wrapperQuery(str));
And these are result of variables in debug mode:
This method is working right, as the decription in the Docs(https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-wrapper-query.html)
The problem is, that this query just not working.
What is wrong and what should I do?
Any comments would be appreciated. Thanks.
Your JSON format seems to be wrong. Since your ASSET_IP is not a number, it must be string in JSON representation. Hence you need to put it as below in your JSON.
{ "ASSET_IP" : "xx.xxx.xxx.xx" }
Update your JSON with the above and try again.

Issue on parsing string at JSON.parse

In controller side i am getting params like
"{\"violation_date\":\"sdfsdf\",\"violation_time\":\"\"},{\"violation_date\":\"sdfdsf\",\"violation_time\":\"sdfsdf\"},{\"violation_date\":\"1233\",\"violation_
time\":\"\"},{\"violation_date\":\"test\",\"violation_time\":\"time\"}"
class of this is String. I am trying to parse this. Through
JSON.parse(params_gotton)
Got
JSON::ParserError (757: unexpected token at ',{"violation_date":"sdfdsf","violation_time":"sdfsdf"},{"violation_date":"1233","violation_time":""},{"violation_d
te":"test","violation_time":"time"}'):
What i am doing wrong here. Any suggestions?
It's not valid json, this will work (use []):
require 'json'
jsn = '[{"violation_date":"sdfsdf","violation_time":""},
{"violation_date":"sdfdsf","violation_time":"sdfsdf"},
{"violation_date":"1233","violation_time":""},
{"violation_date":"test","violation_time":"time"}]'
JSON.parse(jsn) # => [{"violation_date"=>"sdfsdf", "violation_time"=>""}, {"violation_date"=>"sdfdsf", "violation_time"=>"sdfsdf"}, {"violation_date"=>"1233", "violation_time"=>""}, {"violation_date"=>"test", "violation_time"=>"time"}]
To verify json string you could use: http://www.jslint.com/.
And basic json structure: http://json.org/
UPDATED
In your case just try this:
JSON.parse('[' + params_gotton + ']')
well, received string does not contain a proper Json structure..
First convert that received param in a proper json structure and then parse it using "JSON.parse(params_gotton)".
In above received data all key and value shud be in a key value pair string format.. remove "\" symbol from received data..
it will definitely work fine..

Cannot convert Hash to String?

I am trying to parse the JSON response from Wordnik's API. This is built with Sinatra. I keep getting the error "TypeError at /word" "can't convert Hash into String". Am I using the json parser incorrectly?
Here's my code:
get '/word' do
resp = Wordnik.words.get_random_word(:hasDictionaryDef => 'true', :maxCorpusCount => 20, :minLength => 10)
result = JSON.parse(resp)
word = result.word
return word.to_s
end
You are probably getting a hash. To convert it use to_json:
JSON.parse(resp.to_json)
You have not given what's the JSON response that you are parsing. But assuming it is something of the form
{
"word":"my_word"
}
you need to do result["word"] to get the value after parsing the JSON response.

Resources