How can i get JSON objects in the following case:
Here is my post request:
var articles = client.post("http://host:port/path", args, function (data, response) {
// console.log(xml.parseBuffer(data))
console.log(data.toString('utf8'));
// return xml.parseBuffer(data);
});
result of data.toString('utf8') look like:
<WebServiceResponse>
<page>
...
</page>
<articleDataList>
<articleId>
<idArticle>100000</idArticle>
<index>test</index>
</articleId>
<goodType>test</goodType>
<idAttributeSubject>100001</idAttributeSubject>
<identyfiable>false</identyfiable>
<isActive>true</isActive>
<isGoodSet>false</isGoodSet>
<longName>test</longName>
<translationSubjectId>
<idTranslationSubject>100408</idTranslationSubject>
</translationSubjectId>
<unitCode>szt</unitCode>
<vatRate>0.2300</vatRate>
</articleDataList>
<articleDataList>
...
</articleDataList>
<articleDataList>
...
and xml.parseBuffer(data) looks:
{ name: 'articleDataList', childs: [Object] },
I need put into articles objects with only: idArticle, index and shortName
Is there any easy way?
In this output:
{ name: 'articleDataList', childs: [Object] }
Object represents javascript object that you need to stringify like this: JSON.stringify(Object)
Or you should convert this whole Buffer to string first, and then convert to JSON or javascript object:
xml.parseString(data.toString('utf8'))
Related
I have an object like this:
const querystring = require('querystring');
let data = {
name: 'Bill',
hobbies: ['Painting', 'Running']
}
If I encode the object like this:
console.log(querystring.encode(data));
I get this:
name=Bill&hobbies=Painting&hobbies=Running
Then when I decode it:
console.log(querystring.decode(querystring.encode(data));
It comes back perfectly like this:
{
name: 'Bill',
hobbies: ['Painting', 'Running']
}
However if I pass an object with array data that has only one item in it like this:
let data = {
name: 'Bill',
hobbies: ['Painting']
}
When I encode / decode it:
console.log(querystring.decode(querystring.encode(data));
This comes back:
{
name: 'Bill',
hobbies: 'Painting'
}
Notice how it converts the array to a single string, rather than an array with a single item.
Is there anyway around this limitation with querystring? Or is there another module that handles this better? I've been looking around and can't find anything.
my JSON data is like this:
{
notification:{
title: flutter fcm,
body: i got a firebase notification
},
data:{
myKey: myValue
}
}
how should I convert it into a map??
This is the value printed on onMessage() callback of firebase push notification. It is printing on my console. I want to convert this to map. This JSON data's runtimeType is String.
We can use the dart:convert package and the json.decode method to convert a JSON String to a Map:
import 'dart:convert';
final Map<String, dynamic> jsonData = json.decode(jsonData);
I am creating a get api in nodejs.I am requesting the following url
http://localhost:8080/api?id=20&condition1=true&arr=[{prop1:1}]&obj={a:1,b:2}
And I am getting the request query object as follows-
req.query = {
arr:"[{prop1:1}]",
condition1:"true",
id:"20",
obj:"{a:1,b:2}"
}
I want to convert the query object keys to appropriate types.My query object should be converted to
req.query = {
arr:[{prop1:1}], // Array
condition1:true, // Boolean
id:20, // Number
obj: {a:1,b:2} //Object
}
req.query object is dynamic, it can contain any number of objects, array, boolean , number or strings. Is there any way to do it?
This functionality doesn't come out of the box with express and query parameters.
The problem is that in order for the query string parser to know if "true" is actual boolean true or the string "true" it needs some sort of Schema for the query object to help parsing the string.
Option A
What I can recommend is using Joi.
In your case it will look like :
const Joi = require( "joi" );
const querySchema = {
arr: Joi.array(),
condition1: Joi.boolean(),
id: Joi.number(),
obj: {
a: Joi.number(),
b: Joi.number()
}
}
Having this schema you can attach it to your express method and use Joi.validate To validate it.
function getFoo( req, res, next ) {
const query = req.query; // query is { condition1: "true" // string, ... }
Joi.validate( query, querySchema, ( err, values ) => {
values.condition1 === true // converted to boolean
} );
}
Option B
Another way of having properly typed GET requests would be to trick the query parameters and just provide a stringified JSON.
GET localhost/foo?data='{"foo":true,"bar":1}'
This will give you the possibility to just parse the request query
function getFoo( req, res, next ) {
const data = JSON.parse( req.query.data )
data.foo // boolean
data.bar // number
}
I have the next response:
{
"Status": 200,
"Email": "aristos#gmail.com",
"Values": "[\"{\\\"name\\\":\\\"John\\\",\\\"age\\\":30,\\\"ids\\\":[ \\\"123445\\\", \\\"2345456\\\", \\\"42346\\\" ]}\"]"
}
I want to fix this part:
"Values": "[\"{\\\"name\\\":\\\"John\\\",\\\"age\\\":30,\\\"ids\\\":[ \\\"123445\\\", \\\"2345456\\\", \\\"42346\\\" ]}\"]"
So it looks better like this:
{ Status: 200,
Email: 'aristos#gmail.com',
Values: '{"name":"John","age":30,"ids":[ "123445", "2345456", "42346" ]}' }
I'm using node js.
var result={Status: 200,
Email: req.body.email,
Values: req.body.values};
The request is :
email:aristos#gmail.com
values:{"name":"John","age":30,"ids":[ "123445", "2345456", "42346" ]}
a post call
Regards
If you need to use req.body.values is better to use the JSON.parse() method like this:
var val = JSON.parse(req.body.values);
And then your final response String should be stringify using the JSON.stringify() method:
var result={Status: 200,
Email: "email#example.com",
Values: val};
const response = JSON.stringify(result);
Please take a look of this jsfiddle.
Not sure why your data is wrapped into array and stringified, but that's another story.
So, you need to parse a json string, and get 1st array element. Like this:
const response = {
"Status": 200,
"Email": "aristos#gmail.com",
"Values": "[\"{\\\"name\\\":\\\"John\\\",\\\"age\\\":30,\\\"ids\\\":[ \\\"123445\\\", \\\"2345456\\\", \\\"42346\\\" ]}\"]"
};
// now it's parsed and unescaped like - {"name":"John","age":30,"ids":[ "123445", "2345456", "42346" ]}
const values = JSON.parse(response.Values)[0];
response.Values = values;
// From now 'response' object will be as you want
I'm using jquery-1.4.2.min and jquery-ui-1.8.6.custom to get the autocomplete data on a jsp page, here is the code snippet:
$(document).ready(function() { $("input#airportfrom").autocomplete({minLength: 3,
source: function(request, response) { $.ajax({
url: "MLocationLookupSearchPopUpAuto.action?LANGUAGE=${param.LANGUAGE}&SITE=${param.SITE}&RESULT_FILTER=3",
dataType:"text/html",
data: { MATCH : $("#airportfrom").val() },
success: function(data) { response(data); } }); } }); });
The result returned is correct as I have used an alert(data); inside the success function and it gave correct result, but in the list, it is showing one character or one alphabet per line, hence if I want to get LONDON, it is displayed as:
l
o
n
d
o
n
Any idea why this happening ? Whether we have to give data as json only because here I'm getting the data from a jsp.
Try to split the response data into lines using "\n"
$("#tags").autocomplete({
source: function(request,response) {
$.ajax({
dataType: "text",
url: 'yourscript.php?extraParam=foo',
data: { term: request.term },
success: function(data) {
var lines = data.split("\n");
response(lines);
}
})}
});
I had the same problem and it was down to serializing the object twice (by mistake) on the server side. The JSON data returned to the client was being de-serialized to a string rather than an array.