I need to create a JSON object from a json string. I tried JSON.parse(json-string) but I get error:
SyntaxError: Unexpected token o
But when I run the same string in Android JSONObject(json-string) I get a no errors
HTTP.get(url, function (error, response) {
if (response) {
var content = JSON.parse(response);
console.log(content);
Am I doing something wrong? Doesn't response contains the json-string and nothing else un-modified? Thanks
response is an object. You need to JSON.parse(response.content) or just response.data.
From official docs:
Contents of the result object:
statusCode Number
Numeric HTTP result status code, or null on error.
content String
The body of the HTTP response as a string.
data Object or null
If the response headers indicate JSON content, this contains
the body of the document parsed as a JSON object.
headers Object
A dictionary of HTTP headers from the response.
Related
I am using the http client file to do requests in intellij (scratch.http), I want to parse the response and set a global variable. I saw here (https://www.jetbrains.com/help/idea/http-response-handling-examples.html#script-var-example) that I could use this:
POST https://httpbin.org/post
Content-Type: application/json
{
"token": "my-secret-token"
}
//Saving a variable
> {%
client.global.set("auth_token", response.body.json.token);
%}
But there is an issue, the endpoint I need to call returns the header Content-Type:application/json, but it's not really a json, because the response body starts with some characters, and then there is the json, so as an example:
)
]
}',
{
//normal json
}
how can I first slice the first characters of the response, and then parse the json to get the field that I want to set it as a global variable.
In postman I have this:
var jsonData = JSON.parse(responseBody.slice(5));
postman.setEnvironmentVariable("myField", jsonData.myField);
But I don't know how to do it with intellij http client.
Im just a beginner with python but have a plan to working hard to be expert soon:)
I tried to convert to json nad have error:
Response not in valid JSON format
and
class 'requests.models.Response'>
url="https://pl.wikipedia.org/wiki/Wikipedia:Strona_g%C5%82%C3%B3wna"
try:
response = requests.get(url)
if not response.status_code == 200:
print("HTTP error",response.status_code)
else:
try:
import json
response.content.decode('utf-8')
response = json.dumps(response)
loaded_response = json.loads(response)
except:
print("Response not in valid JSON format")
except:
print("Something went wrong with requests.get")
print(type(response))
Response not in valid JSON format means that your response data is not in a valid JSON format.
It's not very clear what you want, but the URL you are requesting https://pl.wikipedia.org/wiki/Wikipedia:Strona_g%C5%82%C3%B3wna does not return JSON formatted data, it returns a full html document (try opening the URL in your browser).
Therefore you cannot convert it to a JSON object.
JSON formatted data would look something like:
{ "name":"John", "age":30, "car":null }
If you would like to test your code you can use a URL from a placeholder service, i.e. https://jsonplaceholder.typicode.com/todos/1
A (GET) request to this URL will return JSON formatted placeholder data so you can test and experiment with your code.
You can learn more about JSON here: https://www.w3schools.com/js/js_json_intro.asp
Good luck!
I had set Content-Type in RequestSpecBuilder as "ContentType.JSON". But on making a GET request, I get Content-Type as "application/xml" in response. How do i get back a json response?
I have tried below approaches:
1. Set content type in RequestSpecBuilder object using setContentType method of RequestSpecBuilder class to "ContentType.JSON" and pass RequestSpecBuilder object in spec method of RequestSpecification --- got "application/xml" in response
Set content type in RequestSpecification object using contentType method of RequestSpecification and pass ContentType.JSON as parameter --- still got "application/xml" in response
Note: The webservice URL requires ".json" to be explicitly specified to get a json response else by default it returns a "xml" response. However, I wanted to set content type by using RequestSpecBuilder.
Eg:
for Json response: URL -- http://ergast.com/api/f1/2017/circuits.json
for Xml response: URL -- http://ergast.com/api/f1/2017/circuits
Code:
#Test
public void test_AddHeader() {
//Use of RequestSpecification
String pathUrl = "http://ergast.com/api/f1/2017/circuits";
RequestSpecBuilder requestSpecBuilder = new RequestSpecBuilder();
requestSpecBuilder = requestSpecBuilder.
setBaseUri(pathUrl).
setContentType(ContentType.JSON).
addQueryParam("limit", "10"); //added query param
RequestSpecification addRequestSpec = requestSpecBuilder.build();
RequestSpecification httpRequest = RestAssured.given().spec(addRequestSpec).contentType(ContentType.JSON);
Response httpResponse = httpRequest.get();
System.out.println(httpResponse.getContentType()); //returns application/xml
System.out.println(httpResponse.getStatusLine()); //returns HTTP/1.1 200 OK
System.out.println(httpResponse.getBody().asString());//returns XML response
}
You are expecting JSON from Response but you are passing setContentType to your RequestSpecBuilder. This will just create your POST payload in json format. It does not do anything to your response.
What you can do instead is Create a ResponseBuilder and do a setContentType to JSON there. Hope this will help you.
I'm setting up a super simple http call to an endpoint on my server which returns a JSON response - an object with a success prop which is a boolean. Here is the relevant code:
getData : Model -> Cmd Msg
getData { userId, data } =
let
url =
"/get-data?userId=" ++ userId ++ "&data=" ++ data
request =
Http.get url decodeGetData
in
Http.send GetDataResult request
decodeGetData : Decode.Decoder Bool
decodeGetData =
Decode.at [ "success" ] Decode.bool
I'm getting the following error from the compiler:
Http.send GetDataResult request
^^^^^^^
Function `send` is expecting the 2nd argument to be:
Http.Request String
But it is:
Http.Request Bool
What's going wrong here? How do I set up Http.send to expect a Bool instead of a string? I know that the basic setup of my request is correct because my code compiles if I change the decodeGetData function to:
decodeGetData : Decode.Decoder String
decodeGetData =
Decode.at [ "success" ] Decode.string
In this case I can successfully make the http request, but then I get an error because the success prop on the response is a boolean instead of a string.
Any pointers? Cheers!
The code you pasted in all looks good, which leads me to think that the problem lies in a piece of code you don't have listed. Namely, the Msg constructor GetDataResult should have a single parameter of type Result Http.Error Bool. The compiler error you received would occur if the signature were instead Result Http.Error String.
Bear with me for any mistakes/wrong terminology since I am new to all this. I am using meteor to develop my project and i need to make a get request to an external API. (I already added meteor add http) Below is my code:
HTTP.call( 'GET', 'url', {}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
If i use the code inside my Client folder in Meteor I get the following error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access meteor It has something to do with CORS which I didn't understand how to implement. If I use the code above in my Server side I do get the correct response in the console but how do I use it as a var on my client javascript code?
Tou can use .call function of HTTP and pass your header in options:
HTTP.call(method, url, [options], [asyncCallback])
Arguments
method String
The HTTP method to use, such as "GET", "POST", or "HEAD".
url String
The URL to retrieve.
asyncCallback Function
Optional callback. If passed, the method runs asynchronously, instead of synchronously, and calls asyncCallback. On the client, this callback is required.
Options
content String
String to use as the HTTP request body.
data Object
JSON-able object to stringify and use as the HTTP request body. Overwrites content.
query String
Query string to go in the URL. Overwrites any query string in url.
params Object
Dictionary of request parameters to be encoded and placed in the URL (for GETs) or request body (for POSTs). If content or data is specified, params will always be placed in the URL.
auth String
HTTP basic authentication string of the form "username:password"
headers Object
Dictionary of strings, headers to add to the HTTP request.
timeout Number
Maximum time in milliseconds to wait for the request before failing. There is no timeout by default.
followRedirects Boolean
If true, transparently follow HTTP redirects. Cannot be set to false on the client. Default true.
npmRequestOptions Object
On the server, HTTP.call is implemented by using the npm request module. Any options in this object will be passed directly to the request invocation.
beforeSend Function
On the client, this will be called before the request is sent to allow for more direct manipulation of the underlying XMLHttpRequest object, which will be passed as the first argument. If the callback returns false, the request will be not be send.
Souce: Here
Fixed it. On client side
Meteor.call("getURL",'url',{},function(err,res){
if(err){
console.log('Error: '+err);
}
if(!err){
console.log('Response: '+res);
}
and on server
Meteor.methods({
'getURL': function(url_l){
console.log("Request: "+url_l)
return HTTP.get(url_l)
}
});