JSON not properly formatting - json

I am trying to have JSON response after querying. I am doing something like this
var result=[];
var reslt={};
reslt["result"]="success"
reslt["token"]=accesstoken
result.push(reslt)
JSON.stringify(result)
res.send(result)
console.log(typeof result)
console.log shows me an object and i got
[1]
0: {
result: "success"
token: "1f4655e3-bf54-49ca-942a-9e61cdfd8f11"
}
but when i try to validate the response on JSONLint it gives me error validating "JSON"

JSON.stringify returns the string, so:
result = JSON.stringify(result)
res.send(result)
or just
res.send(JSON.stringify(result))
Side note: You can simplify that code a fair bit:
res.send(JSON.stringify( [ {result: "success", token: accesstoken} ] ));
or perhaps for clarity:
var result = [ {result: "success", token: accesstoken} ];
res.send(JSON.stringify(result));

Related

Selecting 2nd object in an array in Postman

AH, a very simple question, but I can't seem to find the answer anywhere. This is my first set of postman tests. I have a request that returns this JSON response:
{
"requestId": "3dd0#170fa14fb64",
"result": [
{
"id": 52508,
"status": "deleted"
},
{
"id": 52507,
"status": "deleted"
}
],
"success": true
I want to write a test that verifies that both of the status objects within the result array will have the value "deleted" but I don't know the correct syntax to do so...so far I have this
pm.test("Test users deleted successfully", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.result[0].status).to.eql("deleted");
});
This works great for verifying the first status object, but how do I target the second one in that array?
You would need to loop through the result array:
pm.test("Test users deleted successfully", () => {
var jsonData = pm.response.json();
_.each(jsonData.result, (item) => {
pm.expect(item.status).to.eql("deleted");
});
});
I've used the Lodash .each() function here, which is built-in to Postman, but you can do this with a native JS for loop, it works the same way I just prefer this syntax.
More info:
https://www.w3schools.com/js/js_loop_for.asp

{ "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" }

I am using django-restframework, I use postman POST json data to my project but I got the error like tittle, I have set raw and application/json here is the code from postman.
POST /account/post/reply/ HTTP/1.1
Host: localhost:8000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: a0c7bd93-631e-4c7a-8106-87f018eaf7da
{
"user": "michael",
"userid": "1",
"ihelpid": 6,
"tittle": "6",
"info": "6",
"label": "3",
"tel": "dxy970525",
"picture1": null,
"picture2": null
}
my code is really easy only like :
from rest_framework.parsers import JSONParser,ParseError
class ReplyViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
"""
pagination_class=PageNumberPagination
queryset = Forum_reply.objects.all()
serializer_class = ReplySerializer
#filter
filter_backends = (DjangoFilterBackend, )
filter_fields = ['postID',]
def create(self, request, *args, **kwargs):
print(request.data)
data = JSONParser().parse(request)
return HttpResponse("ok")
After I use viewsets,this error occur,I have print it on shell but it is no problem
I actually had the same error, you need to use JSON.stringify(data) like the following in case you are using ajax :
datato= {
"id" : 3,
"title" : "level up",
"author" : "jason rock"
}
$.ajax({
method:'POST',
url:"/home/api",
data : JSON.stringify(datato),
})
#SeriForte 's answer pointed me in the right way
In my case, i was not sending a correct json in the data. So please check that.
I have solved this problem,I can access data now
I changed my older code
print(request.data)
data = JSONParser().parse(request)
this will get an error. If I code like below:
print(request)
data = JSONParser().parse(request)
Then I can access data in the dictionary.
So, I did not know why but the issue is fixed
if you use a Javascript fetch request, you have to stringify the JSON Data object like so
let data = {
"key1": 1,
"key2": "text"
}
fetch(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
'X-CSRFToken': csrftoken
},
body: JSON.stringify(data) // <-- do not include the Json array directly
}).then(function (response) {
// ...
console.log(response);
return response.json();
}).then(function (body) {
// ...
console.log(body);
}).catch(err => {
console.log(err)
})
If you're using postman it's not possible to put comments in the body > raw section.
Like this
So it is better to remove the commented part out.
HTH

retrieving the response of a POST in NodeJS

I am receiving below response from a service
[ { recipient_id: 'default',
text: 'Hello, how can I help?' } ]
I need to retrieve the text portion of the response. I can do that with python like below
json_response = response.json()
reply = json_response[0]['text']
But I need to retrieve the text portion in NodeJS now for a different project. So I have tried below code but it outputs undefined
var obj = JSON.parse(response)
console.log(obj[0]['text'])
Can anyone please suggest?
EDIT:
The POST request is made like
request.post(
'http://path-to-service',
{ json: { 'query': msg} },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
var obj = JSON.parse(body)
console.log(obj[0]['text'])
}
The problem is the service returns response as an array of python dictionary. So response[0] is essentially a python dictionary
{ recipient_id: 'default',
text: 'Hello, how can I help?' }
So the question is, how do I retrieve the value of the key text from this dictionary.
I think your response is already coming as JSON object so don't need to parse again.
var obj = [ { recipient_id: 'default',
text: 'Hello, how can I help?' } ];
console.log(obj[0].text);
try code
var body = {'query': 'msg', 'name': 'my name is nodejs'}
var obj = JSON.parse(body);
console.log(obj.query);
console.log(obj.name);
printf
msg
my name is nodejs

Multi level json with body response in nodjs

I make a request to REST Server with NodeJS and getting this type of JSON in my 'body'
[{
"id": 802,
"created": "2016-10-18 15:22:08",
"test": {
"name": "Fred "
}
}]
log my body with JSON.parse, that is working fine for the 'root' of the JSON, but I'm not getting the 'name' in the 'test' array
var jsonObj = JSON.parse(body);
for(index in jsonObj) {
console.log(jsonObj[index].bag);
How can I make the loop and if there is a 'test' getting the data keys out ??
This code should work given your JSON description
var jsonObj = JSON.parse(body);
for(index in jsonObj) {
console.log(jsonObj[index].test.name);

How to return a JSON object from an Azure Function with Node.js

With Azure Functions, what do you need to do to return a JSON object in the body from a function written in node.js? I can easily return a string, but when I try to return a json object as shown below I appear to have nothing returned.
context.res = {
body: jsonData,
contentType: 'application/json'
};
Based on my recent testing (March 2017). You have to explicitly add content type to response headers to get json back otherwise data shows-up as XML in browser.
"Content-Type":"application/json"
res = {
status: 200, /* Defaults to 200 */
body: {message: "Hello " + (req.query.name || req.body.name)},
headers: {
'Content-Type': 'application/json'
}
};
Full Sample below:
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
context.log(context);
if (req.query.name || (req.body && req.body.name)) {
res = {
// status: 200, /* Defaults to 200 */
body: {message: "Hello " + (req.query.name || req.body.name)},
headers: {
'Content-Type': 'application/json'
}
};
}
else {
res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
context.done(null, res);
};
If your data is a JS object, then this should just work, e.g.
module.exports = function(context, req) {
context.res = {
body: { name: "Azure Functions" }
};
context.done();
};
This will return an application/json response.
If instead you have your data in a json string, you can have:
module.exports = function(context, req) {
context.res = {
body: '{ "name": "Azure Functions" }'
};
context.done();
};
Which will return an application/json response because it sniffs that it is valid json.
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
if (req.query.name || (req.body && req.body.name)) {
context.res = {
// status: 200, /* Defaults to 200 */
body: {"data":"Hello"},
headers: {
'Content-Type': 'application/json'
}
};
}
else {
// res = {
// status: 400,
// body: "Please pass a name on the query string or in the request body"
// };
}
context.done(null,res);
I would like to add one more point. Apart from making the body: a JSON object, the request should also contain proper headers telling server what content type we are interested in. I could see that same Azure function when just invoked via browser using URL gives XML response, but when invoking from script or tools like Postman it gives JSON.
I feel like the answer has been given but it hasn't been clearly presented so I thought I'd answer as well in case it will help anyone coming behind me. I too have created a function that most definitely returns a Javascript object but if I copy and paste the URL in the Azure Function UI and just open a new tab in Chrome and try to view the output, I actually get back an XML document that tells me there's an error (not surprising there's an error as many characters in the Javascript would have blown up the XML). So, as others have mentioned, the key is sending the appropriate headers with your request. When you copy/paste the URL into your browser, the browser is sending a request header that looks similar to this:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
When that happens, you see the XML return as described in this link:
https://github.com/strongloop/strong-remoting/issues/118
In order to get around this problem and see what the data would look like with a JSON request, either use a utility like Postman:
https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
Accept: application/json
Or use a CURL command and pass in the proper Accept header.
As you can see in the screenshot above, when I provided the proper header, I get back the JSON response I would expect.
You can also use JSON.stringify() to make a valid json string out of your js-object:
jsonData = { value: "test" }:
context.res = {
body: JSON.stringify(jsonData)
};