Multi level json with body response in nodjs - json

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

Related

uploading image using file_picker flutter to a nodejs server

I have an api which gives the following data as response:
{
"status": 200,
"msg": "Data Found",
"data": {
"id": 104,
"firstName": "aaa",
"lastName": "aaa",
"surname": "aaa",
"email": "email#email.care",
"phone": "090909090",
"age": "23",
"gender": "M",
"height": "163",
"bloodGroup": null,
"weight": "72",
"status": null,
"fileId": 228,
"password": "pass",
"file": {
"id": 228,
"filename": "images.jpg",
"path": "user/images1613558976577.jpg",
"alt": "shafa care"
}
},
"success": true,
"token": "some token",
"userAccess": "some data"
}
The "file" parameter in the response is used to hold the image that the user uploads. For my update method, the user needs to pass their token as header for the update api. For updating the file parameter i have tried many different ways just to update the user image. The below code is using multipart form data to update the existing file image.
Future<AuthModel> updateImage(File imageFile, AuthModel authModel) async{
final String _accessToken = '${authModel.token}';
final String url =
'${GlobalConfiguration().getString('api_base_url')}auth/user/update';
var stream = new http.ByteStream(imageFile.openRead());
var length = await imageFile.length();
var uri = Uri.parse(url);
var request = new http.MultipartRequest("POST", uri);
request.headers['Authorization'] = _accessToken;
// request.headers['Content-Type'] = 'multipart/form-data';
var multipartFile = new http.MultipartFile('file', stream, length, filename: basename(imageFile.path));
request.files.add(multipartFile);
var response = await request.send();
print("updating: " + response.statusCode.toString());
response.stream.transform(utf8.decoder).listen((event) {
currentUser = authModelFromJson(event);
print("updating img: " + event);
});
return currentUser;
}
The above function does not update my file parameter even when the data is found. I just get the same old response. filepicker is also sending the correct image path that the user chooses from the gallery. I have also tried using http.client.post method using a token as the header and 'file' parameter as the body but then data is not found as the api only accepts form-data when an image is being uploaded.
It works in postman using form-data post method.
I am new to flutter and still learning. I have been stuck here for days without any solution. How can i update the file parameter from my flutter application? Any help is appreciated.
This is sample code. I hope this may help you !
static Future<bool> uploadFileAsFormData(
String url, File file) async {
try {
var uri = Uri.parse(_buildUrl(url));
var request = http.MultipartRequest('POST', uri);
request.files.add(await http.MultipartFile.fromPath('file', file.path));
var res = await request.send();
if (res.statusCode == 200) {
return true;
} else {
return false;
}
} catch (err) {
return false;
}
}
You can use this Dio to upload the image as shown by the following code:
Dio dio = Dio();
var formData = FormData();
for (var file in filePath) {
formData.files.addAll([MapEntry("files", await MultipartFile.fromFile(file)),]);
print(formData.length);
}
var response = await dio.post(url
data: formData,
options: Options(headers: {
'Authorization': _accessToken
}));
if(response.statusCode == 200){
print(response.data.toString();
}

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

Modifying the json response - WEbAPI

I am returning the object directly in the GET request as following.
Ok(object);
and the response json is given as,
json data-->
{
"id":"1",
"name":"testname"
}
I want to add some more details to this json
-->
{
success:"true",
messageDetails:"The response is returned by the service",
data:{}
}
how to accomplish this?
can i club all the things in Ok(object) ??
You can make use of an anonymous type, for example:
object data = new { id = 1, name = "testname" };
return Ok(new
{
success = "true",
messageDetails = "The response is returned by the service",
data
});

Parse JSON file containing multiple objects

I have a JSON file that contains multiple objects of the same structure that look like this:
{
"id": "123",
"type": "alpha"
}
{
"id": "321",
"type": "beta"
}
I'm using node.js to read the file.
fs.readFile(__dirname + "/filename.json", 'utf8', function(err, data) {
var content = JSON.parse(JSON.stringify(data));
If I do a console.log(content) things look good. I see the content of the json file. I'm trying to iterate over each object but I'm not sure how to do that. I've tried using
for(var doc in content)
but the doc isn't each object as I was expecting. How do I loop over the content to get each object in a json format so that I can parse it?
If content is an array, you can use
content.forEach(function (obj, index) { /* your code */ })
See documentation for Array.prototype.forEach()
if you need to just iterate, a forEach loop would work or a normal for loop :
for(var i = 0; i<content.length(); i++){
//perform whatever you need on the following object
var myobject = content[i];
}
Depend of the files, the two current answer (Osama and Daniel) assume you have a JSON Array:
[
{
"id": "123",
"type": "alpha"
},
{
"id": "456",
"type": "beta"
}
]
In which case, you can use any array iterator:
var async = require('async'),
content = require(__dirname + "/filename.json");
async.each(content, function (item, callback) {
//...
});
But in your case, it seems to not be JSON (no bracket to indicate array, and no comma to separate the objects), so in the case JSON.parse doesn t throw up any error, you'll need to isolate your objects first:
var fs = require('fs'),
async = require('async');
fs.readFile(__dirname + "/filename.notjson", 'utf8', function(err, data) {
var content = data.split('}');
async.map(content, function (item, callback) {
callback(null, JSON.parse(item));
}, function (err, content) {
console.log(content);
};
});

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