Can't access JSON value from curl - json

I use this curl command:
curl -X POST -H "Content-Type: application/json" http://localhost:8081/creditcard -d '{"credit-card":"1234-5678-9101-1121"}'
In my js file, I have this code block to get the credit-card's value:
request.on('data', function(data) {
var cc = 'credit-card';
var a = JSON.parse(data.toString());
console.log(a[cc]);
}
For this I get:
undefined:1
'{credit-card:1234-5678-9101-1121}'
^
SyntaxError: Unexpected token '
at Object.parse (native)
at IncomingMessage.<anonymous> (<path>\ccserver.js:32:34)
at IncomingMessage.emit (events.js:107:17)
at IncomingMessage.Readable.read (_stream_readable.js:373:10)
at flow (_stream_readable.js:750:26)
at resume_ (_stream_readable.js:730:3)
at _stream_readable.js:717:7
at process._tickCallback (node.js:355:11)
So I tried to use JSON.stringify as followed:
request.on('data', function(data) {
var cc = 'credit-card';
var a = JSON.parse(JSON.stringify(data.toString()));
console.log(a[cc]);
}
But this is what I get:
undefined
undefined
However, when I try to parse a hard-coded json string, it goes ok:
var jsonString = '{"credit-card":"1234-5678-9101-1121"}';
var a = JSON.parse(jsonString);
console.log(a[cc]);
Result:
1234-5678-9101-1121
What is the correct way to do get the data out of this json?
Please advise
Thanks

Try reading from absolute path
curl -X POST
-H 'Content-Type:application/json'
-H 'Accept: application/json'
--data-binary #/full/path/to/test.json
http://server:port/xyz/abc/blah -v -s
Well, you already have String so all you need to convert it to javascript variable and get using .notation. Suggest to use firebug to see what is in variable.
obj = JSON.parse(json);
obj.cc or obj.cc[0]
should give you what you want.

Related

Jenkins : Extract data from Jira curl

I use a curl to get the status of a Jira issue :
result = sh(returnStdout: true, script: """curl -D- -k -u $JIRA_LOGIN:$JIRA_PWD -X GET -H "Content-Type: application/json" $url""")
This returns a String like :
{"expand":"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations","id":"*****","self":"*****","key":"*****","fields":{"status":{"self":"*****","description":"Issues in development","iconUrl":"****","name":"DEVELOPMENT","id":"10400","statusCategory":{"self":"****","id":4,"key":"indeterminate","colorName":"yellow","name":"In Progress"}}}}
How I can extract the data "DEVELOPMENT" in this string ? I try to parse it in JSON but it's not working :
status_json = new JsonSlurper().parse(result)
with the error "java.io.NotSerializableException: groovy.json.JsonSlurper"
You can check out the JsonSlurper's documentation:
Jira holds all issue fields under the "fields" key in JSON. So, after you get the JSON, you just need to go to the fields.status.name in order to get "DEVELOPMENT" text.
Here's a simple approach:
def jsonSlurper = new JsonSlurper()
def issueObj = jsonSlurper.parseText('...') // Your Jira response will be here
issueObj.fields.status.name // It will give you the status' name.

LWP response JSON values are empty

I'm trying to run GET method using LWP and CURL (unix command) to get the content in JSON format, I'm seeing the complete content only in CURL command but the LWP response is showing valid JSON but with empty values.
REQUEST
LWP
my $ua= LWP::UserAgent->new();
my $host='https://sample.com/iersiefhsiof';
$ua->default_header('Content-Type' => 'application/json');
$ua->default_header('Authorization' => 'XXXXXXXXXXXXXXxx');
$ua->default_header('Accept' => 'application/json');
my $response=$ua->get($host);
$res=$response->content();
print ($res);
CURL
curl -H "Accept: application/json" -H "Content-Type: application/json" -H 'Authorization:XXXXXXXXXXXXXXX' -ikL 'https://sample.com/iersiefhsiof'
RESPONSE
LWP
{
"id":"",
"state":"",
"category":"",
"severity":"",}'`
CURL
`{"id":"iersiefhsiof","state":"open","category":"App","severity":"minor",}'`
Please help me to understand what I'm missing in LWP request to get the complete response content.
It is fixed now !
As per Header.pm , I should use ":" for custom header field name , if I'm not using that then it is converting the first characters as Uppercase and hence the header is missed.
unless ($field =~ /^:/) {
$field =~ tr/_/-/ if $TRANSLATE_UNDERSCORE;
my $old = $field;
$field = lc $field;
unless($standard_case{$field} || $self->{'::std_case'}{$field}) {
# generate a %std_case entry for this field
**$old =~ s/\b(\w)/\u$1/g;**
$self->{'::std_case'}{$field} = $old;
}
}
Refer: https://github.com/libwww-perl/HTTP-Message/blob/master/lib/HTTP/Headers.pm
':x-inf-route-key'=>'GetID'
Thanks :)

Grails command object and 404 when space inside JSON from CURL

I have inherited a controller.
When a post request is made, with a well structured JSON document everything is fine.
When the JSON contains a space in a feld, 404 is returned.
However, when the same request is made from mozilla restclient extension everything works.
The CURL request specifically is:
curl --include \
--request POST \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data-binary "{
"planCode" : "My Test App-standard"
}" \
"https://localhost/signupApi/v2/signup"
URLMapping:
"/signupApi/v2/$action"{
parseRequest = true // parse json, and assign to params
controller = "signupApiSignup"
}
So, why would a space in curl cause problems in the request body that grails receives?
Thanks
You are not quoting your strings there properly in your shell. Use ' for your parameters, if you plan to use "sensitive" chars like " there. Or use \" inside. Also curl can read a filename if you prefix it with # instead of the actual data.
Yet in this case maybe quoting with ' is easiest. E.g.:
...
--data-binary '{
"planCode" : "My Test App-standard"
}'
...

Upload file in BOX using BOX API using C#

I have BOX account and in API document
curl https://upload.box.com/api/2.0/files/content \
-H "Authorization: Bearer ACCESS_TOKEN" \
-F filename=#FILE_NAME \
-F parent_id=PARENT_FOLDER_ID
I am stuck with this filename and parent_id how to pass the filename and parent_id
i have tried lots of way, but nothing is working for me.
Following is the code:
httpWReq.Method = "POST";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "multipart/form-data";
//{\"parent_id\":\""+parentID +"\"}
//byte[] file = File.ReadAllBytes(postData);
httpWReq.ContentLength = data.Length;
using (Stream reqStream = httpWReq.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
//reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse())
{
//Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
response.Close();
}
Need Help
Thanks in Advance
Vaibhav,
Please see example of how official Box C# SDK is doing upload:
https://github.com/box/box-windows-sdk-v2/blob/master/Box.V2/Managers/BoxFilesManager.cs
Is there any reason why you don't want to use Box Windows SDK?

Simple JSON request with cURL to Mochiweb

I have a very simple 'hello world' Mochiweb server (I just started my introduction into it), which takes a JSON request and sends it back:
'POST' ->
case Path of
"dummy" ->
Data = Req:parse_post(),
Json = proplists:get_value("json", Data),
Struct = mochijson2:decode(Json),
Action_value = struct:get_value(<<"action">>, Struct),
Action = list_to_atom(binary_to_list(A)),
Result = [got_json_request, Action],
DataOut = mochijson2:encode(Result),
Req:ok({"application/json",[],[Result]});
The thing is that when I try to make a request to it with cURL it fails:
curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"action":"dummy"}' http://localhost:8080/dummy
The Mochiweb log is quite difficult to read, but as I understand the error happens at this line:
Json = proplists:get_value("json", Data)
I have put a couple of io:formats in the code and found out that both Data and Json variables are [] after I make a request with cURL.
On the other hand, when I do a very simple request with cURL:
curl -d '{"action":"dummy"}' http://localhost:8080/dummy
both Data and Json are [{"{\"action\":\"dummy\"}",[]}], but in that case the line Struct = mochijson2:decode(Json) fails.
For some strange reason Mochiweb does not see the JSON data in the POST request in case the header has the "application/json" value.
So, the question is: How do I make a correct POST request with JSON data to a Mochiweb server?
EDIT: Json variable has the undefined value.
Try something along the lines of
Data = Req:recv_body(),
Json = mochijson2:decode(Data),
...
You should at least ensure method post and the content type ahead of this.
This is not about POST nor get.
It's about how you post your data to send to your server
When you send a json data to server, you need to make it as key=value
curl -d "key=value" "http://your.domain.com/path"
Therefore, if you want to post json as '{"action":"dummy"}', for GET request
curl -d "json='{\"action\":\"dummy\"}'" http://localhost:8080/dummy
For POST request as a file,
curl -F "json=#filename.json" http://localhost:8080/dummy
of course, when you send as a file, you need to read the posted file from the server side.