retrieving the response of a POST in NodeJS - json

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

Related

How to dynamically read external json files in node.js?

I am creating a website that reads externally hosted json files and then uses node.js to populate the sites content.
Just to demonstrate what I'm after, this is a really simplified version of what I'm trying to do in node.js
var ids = [111, 222, 333];
ids.forEach(function(id){
var json = getJSONsomehow('http://www.website.com/'+id+'.json');
buildPageContent(json);
});
Is what I want to do possible?
(Marked as a duplicate of "How do I return the response from an asynchronous call?" see my comment below for my rebuttal)
You are trying to get it synchronously. What you should aim for instead, is not a function used like this:
var json = getJSONsomehow('http://www.website.com/'+id+'.json');
but more like this:
getJSONsomehow('http://www.website.com/'+id+'.json', function (err, json) {
if (err) {
// error
} else {
// your json can be used here
}
});
or like this:
getJSONsomehow('http://www.website.com/'+id+'.json')
.then(function (json) {
// you can use your json here
})
.catch(function (err) {
// error
});
You can use the request module to get your data with something like this:
var request = require('request');
var url = 'http://www.website.com/'+id+'.json';
request.get({url: url, json: true}, (err, res, data) => {
if (err) {
// handle error
} else if (res.statusCode === 200) {
// you can use data here - already parsed as json
} else {
// response other than 200 OK
}
});
For a working example see this answer.
For more info see: https://www.npmjs.com/package/request
I think problem is in async request. Function will return result before request finished.
AJAX_req.open( "GET", url, true );
Third parameter specified async request.
You should add handler and do all you want after request finished.
For example:
function AJAX_JSON_Req( url ) {
var AJAX_req = new XMLHttpRequest.XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function() {
if (AJAX_req.readyState == 4 && AJAX_req.status == 200) {
console.log(AJAX_req.responseText);
}
};
}

Parsing JSON object sent through AJAX in Django

This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'

Mapping http response from node to json file

I am working on a solution where the web server (node with express) will be using request package to fetch data from a web api.
The data return (if contains validation error status code), will be matched again the value and return the corresponding error message. How could it be achieve?
It would be something like this:
var options = {
method: 'POST',
url: 'apiUrl'
}
var response = function (error, response, body) {
if(!error && response.statusCode == 200){
res.jsonp(body);
} else {
if (body.language == 'en') {
// map the reponse body error status code to en.json
} else if (body.language == 'jp')
// map the response body error status code to jp.json
}
}
request({
options, response
})
Default body response for validation error
{
'language': 'en',
'error': [{ 'ErrorCode': '1000', 'ErrorCode': '1001'}]
}
Final body response (after processing)
{
'language': 'en',
'error': [{'ErrorMessage': 'Invalid data format', 'ErrorMessage': 'Invalid Password'}]
}
Resource file for different language of validation (static in server)
en.json
{
'1000': 'Invalid date format',
'1001': 'Invalid password',
'1002': ...
'1003': ...
...
'1999': ...
}
jp.json
{
'1000': 'japan translation',
'1001': 'japan translation 2',
'1002': ...
'1003': ...
...
'1999': ...
}
Here you see how to it.
I'm using fs module to open the JSON file. and I'm using map to convert the errorCode array to errorMessage array
var response = function(error, response, body) {
if (!error && response.statusCode == 200) {
res.jsonp(body);
} else {
// Set defaut language.
if (!body.language.match(/en|jp|iw/)) body.language = 'en'
// You must specify default language for security reasons.
// Open the file, and convert to JSON object
var j = JSON.parse(
require('fs').readFileSync(__dirname + '/' + body.language + '.json')
)
res.jsonp({
language: body.language,
// Convert error:[{errorCode}] array to the messages from the JSON
error: body.error.map(function(v) {
return j[v.ErrorCode]
})
})
}
}

JSON output formatting

I am trying to format the JSON output through node js as shown below
[{"headers":["id","name","description","type","actionmode","outputparser","dispatchtype","troubleticketaction","alarmaction","actionexecutionmode","cost","isparent__"],"values":["100","test_bsc_interface","test_bsc_interface","test","Open Loop","regex","HPSA",null,null,"Asynchronous",null,"0"]},["101","check_tt","check_tt","test","Open Loop","None","Trouble Ticket","check_tt",null,"Synchronous",null,"0"]}
But currently i am getting the output as shown below
[{"headers":["id","name","description","type","actionmode","outputparser","dispatchtype","troubleticketaction","alarmaction","actionexecutionmode","cost","isparent__"],"values":["100","test_bsc_interface","test_bsc_interface","test","Open Loop","regex","HPSA",null,null,"Asynchronous",null,"0"]},{"headers":["id","name","description","type","actionmode","outputparser","dispatchtype","troubleticketaction","alarmaction","actionexecutionmode","cost","isparent__"],"values":["101","check_tt","check_tt","test","Open Loop","None","Trouble Ticket","check_tt",null,"Synchronous",null,"0"]}
Please find code snippet that i have used : may know whats the changes required in the code ::
var json_string=JSON.stringify(rows,null,2);
var json_object=setValue(JSON.parse(json_string));
if (!err){
console.log('The object are returning ',json_object);
var result = _.map(json_object, function(o) {
return {headers: _.keys(o), values : _.values(o)}
});
Your problem seems to be from another post I answered:
How to format the JSON object key/value pair
var json_string=JSON.stringify(rows,null,2);
var json_object=setValue(JSON.parse(json_string));
var result;
if (!err){
console.log('The object are returning ',json_object);
if (_.isArray(json_object) && json_object.length > 0) {
result = {
headers: _.keys(json_object[0]),
values: _.map(json_object, function(o) {
return _.values(o);
})
};
}
}

JSON not properly formatting

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