Mulesoft : HTML to JSON conversion? - html

Is it possible to convert an html input to JSON using mulesoft?
For my case specifically, I am trying to convert an HTML table to JSON arrays.
Input:
<table>
<tr><td>id</td><td>value1</td><td>value2</td></tr>
<tr><td>0 </td><td>0 </td><td>0 </td></tr>
<tr><td>0 </td><td>1.5 </td><td>2.15 </td></tr>
</table>
Output:
"JsonOutput" :[
{id:"0",value1:"0",value2:"0"},
{id:"1",value1:"1.5",value2:"2.15"}
]

What you can do is fetch the top tr element from the table and use it to determine the headers. Then you can create the JSON dynamically using that headers array.
%dw 2.0
var tableAsArray = payload.table.*tr
var tableHeaderRow = tableAsArray[0].*td
var tableValuesRow = tableAsArray[1 to -1]
output application/json
---
{
"JsonOutput": tableValuesRow map ((tr) -> {
(tr.*td map ((td, index) -> {
(tableHeaderRow[index]): td
}))
})
}

Related

xml2js - xml tag values converted to array of jsons

I am using the following code to convert xml to json :-
var parseString = require('xml2js').parseString;
var xml = "<root><param_name>Hello</param_name><param_entry> xml2js! </param_entry> </root>";
parseString(xml, {trim: true},function(err,result){
console.dir(JSON.stringify(result));
});
It is returning the following result -
{
"root":{
"param_name":[
"Hello"
],
"param_entry":[
" xml2js!"
]
}
}
It is returning value of as collection of objects i.e. as "param_name":[
"Hello"
].
But I want it as a simple key and value form.
That is my resultant JSON should look like -
{
"root":{
"param_name":
"Hello"
,
"param_entry":
" xml2js!"
}
}
What is it that is going wrong here ?
The solution is to - use the {explicitArray:false} option for the parser as follows:
var xml2js = require('xml2js');
var parser = new xml2js.Parser({explicitArray : false});
var xml = "<root><param_name>Hello</param_name><param_entry> xml2js! </param_entry> </root>";
parser.parseString(xml,function(err,result){
console.dir(JSON.stringify(result));
});
As per npm doc of xml2js - by default it is set to "true" - so all child nodes are put in an array.
By setting this as "false" - child nodes are added into an array if they are present multiple times.
i.e multiple tags are present.

Nested CSV - Mule DataWeave

I have a CSV like this:
data1,data2,data3;dataa;datab;datac;datax,datay,dataz
data1,data2,data3;dataa;datab;datac;datax,datay,dataz
data1,data2,data3;dataa;datab;datac;datax,datay,dataz
I use spliter to process the records line by line, further I use splitBy "," in dataweave to convert the record to a map. But how I can do another level of split for ";" ? SplitBy doesnt allow muliple delimiters so do the CSV type in dataweave.
Ultimately, I want a JSON like this:
{
"1":"data1",
"2":"data2",
"3":{
"a":"dataa",
"b":"datab",
"c":"datac"
},
"x":"datax",
"y":"datay",
"z":"dataz "
}
Any thoughts ?
Try the following DataWeave code:
%dw 1.0
%output application/json
---
payload map {
"1": $[0],
"2": $[1],
"3": using (detail = $[2] splitBy ";") {
a: detail[1],
b: detail[2],
c: detail[3]
},
x: $[3],
y: $[4],
z: $[5]
}
Notes:
I modified the input data to separate datac and datax. Replace the ; character with , e.g.: ...;datab;datac,datax,...
I use File connector to read the CSV file, and directly process it in DataWeave transformer (do not use a Splitter)
I want to observe, that your JSON example has bad structure!
In this JSON the 4th element is an object and it hasn't a key, just value...
First of all, u should validate your end JSON.
Example of your valid JSON:
When u validate your JSON, I'll try to help in convering your CSV data to the JSON.

How do we use a JSON result from $http.get in Angular?

I'm getting a json using $http.$get, but to it be "compatible" with Angular, I'm having to convert it this way:
$http.get('/api/v1.0/plans').
success(function(data) {
var plans = [];
for(var propertyName in data)
{
if (data.hasOwnProperty(propertyName))
{
plans.push(data[propertyName]);
}
}
$scope.plans = angular.fromJson(data);
});
But, of course, I think this would be the way to go in this case, as shown in docs:
$http.get('/api/v1.0/plans').
success(function(data) {
$scope.plans = data;
});
I can see the difference between the objects, I just don't know how to fix it:
data (not accepted by angular)
Object {alfa: Object, beta: Object, delta: Object, omega: Object}
plans (converted and accepted by angular)
[Object, Object, Object, Object]
Could you, please, tell what I'm doing wrong?
You need to elaborate a bit more about what kind of "compatible" problem you refered to in your first sentence. As far as I know, both JSON representations work just fine in Angular for me.
I believe the question here boils down to how the data will be used after being set to $scope.plans. If you are trying to use ng-repeat with $scope.plans afterward, then how you iterate will differ slightly depending whether the data you receive is a JSON object or JSON array.
For JSON object, you use
<tr ng-repeat="(name, plan) in plans">
<td> {{name}} </td> <td> {{ plan | json }} </td>
</tr>
For JSON array, you use
<tr ng-repeat="plan in plans">
<td> {{$index}} </td> <td> {{ plan | json }} </td>
</tr>
Of course, for plan specified in HTML snippets above, you can access object inner fields with dot notation as usual (i.e., {{plan.title}}, {{plan.description}}, etc.). {{plan | json}} just converts JSON object into string so you can see object content directly in HTML.
For details on how to use ngRepeat, you can read more at https://docs.angularjs.org/api/ng/directive/ngRepeat
In case a (Object {alfa: Object, beta: Object, delta: Object, omega: Object} your api return object so you have to define plans as a object not array that should works
$scope.plans = {}; // <-object
$http.get('/api/v1.0/plans').
success(function(data) {
angular.copy(data, $scope.plans);
});
in case you api will return array of object you have to define plans as a array ie:
$scope.plans = []; // <-array
$http.get('/api/v1.0/plans').
success(function(data) {
angular.copy(data, $scope.plans);
});
Please see bin here

how to convert a json object into json array

I am getting json from asana that is an object (data) of several objects. How do I make data an array?
{"data":{"id":5571422294129,"created_at":"2013-05-24T15:31:50.340Z","modified_at":"2013-05-24T15:32:21.260Z","name":"testProject","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}}
I am trying to put this in a data table using aoColumns. If there is no need to convert "data" to an array please let me know how to use this JSON in datatables without it.
It is not that complicated. You can use DataTables aaData for this. I assume your JSON contains multiple "data":{..}, "data":{..}, "data":{..} ?
Then, consider this as test data :
var data = [
{"data":{"id":1571422294129,"created_at":"2010-05-24T15:31:50.340Z","modified_at":"2010-05-24T15:32:21.260Z","name":"testProject","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}},
{"data":{"id":2571422294129,"created_at":"2011-05-24T15:31:50.340Z","modified_at":"2011-05-24T15:32:21.260Z","name":"Project A","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}},
{"data":{"id":3571422294129,"created_at":"2012-05-24T15:31:50.340Z","modified_at":"2012-05-24T15:32:21.260Z","name":"Project B","notes":"bla bla","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}}
];
HTML markup
<table id="test">
<thead>
<tr>
<th>archived</th>
<th>created_at</th>
<th>id</th>
<th>modified_at</th>
<th>name</th>
<th>notes</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
convert JSON to aaData-array :
var aaData = [];
for (var i=0;i<data.length;i++) {
aaData.push([
data[i].data.archived,
data[i].data.created_at,
data[i].data.id,
data[i].data.modified_at,
data[i].data.name,
data[i].data.notes
]);
}
Initialize the table
$('#test').dataTable({
"aaData": aaData
});
result :
I am not sure what you are exactly attempting to do, but...
If you are trying to deserialize the JSON into a data table you want something like this. This will take your JSON and deserialize it to an object, it won't exactly work with a data table but rather custom classes decorated with DataContract and DataMember attributes. But I think it may be a good starting point for you.
Public static T DeSerialize<T>(string strJSON)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strJSON));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
return (obj);
}
Here is a very useful article regarding serializing JSON. HTH :)
http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx
Regards

Convert JSON object to array?

I have this on my console on firebug,
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...}, Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
it is data from the server side. Now, how would I convert this into array such that this data can be used on another file. I tried JSON.parse and jQuery.parseJSON but both did not work.
That isn't JSON it's a Javascript array of objects, not a string. My guess is that you've received this from a jQuery ajax call and you had the dataType : 'json' set so that jQuery has automatically parsed the JSON into this array.
To send it to a PHP script you can convert it back to JSON using:
var myString = JSON.stringify(data);
and then fire off an ajax call to the PHP script with that as the POST data:
var myString = JSON.stringify(data);
$.post('page.php', { data : myString }, function(){
console.log( "sent" );
});
In PHP you can decode it using:
$data = json_decode($_POST['data']); // <-- or whatever your post variable is named
foreach($data as $obj)
{
echo $obj->fa_id;
}
if you want to get an php array use this
http://php.net/manual/en/function.json-decode.php
The string you provided is not valid JSON.
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...},
Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
In particular, the "Object" and "more..." strings cannot be interpreted by a JSON parser.
Assuming the object you are inspecting is a variable named foo:
console.log(JSON.stringify(foo));
Should print a valid JSON representation of your object to the Javascript console.