Angular - Convert Jackson output to JSON - javascript

The server I'm working with changed the REST format from plain JSON:
{
"removedVertices": [
{
"id": "1",
"info": {
"host": "myhost",
"port": "1111"
},
"name": "Roy",
"type": "Worker"
}
],
"id": "2",
"time": 1481183401573
}
To Jackson format:
{
"removedVertices": [
"java.util.ArrayList",
[
{
"id": "1",
"info": [
"java.util.HashMap",
{
"host": "myhost",
"port": "1111"
}
]
"name": "Roy",
"type": "Worker",
}
]
"id": "2",
"time": 1482392323858
}
How can I parse it the way it was before in Angular/Javascript?

Assuming only arrays are affected, I would use underscore.js and write a recursive function to remove the Jackson type.
function jackson2json(input) {
return _.mapObject(input, function(val, key) {
if (_.isArray(val) && val.length > 1) {
// discard the Jackson type and keep the 2nd element of the array
return val[1];
}
else if (_.isObject(val)) {
// apply the transformation recursively
return jackson2json(val);
}
else {
// keep the value unchanged (i.e. primitive types)
return val;
}
});
}

If the api should be restful, then the server should not return none plain json results. I think the server site need to fix that.
I think it is because the server enabled the Polymorphic Type Handling feature.
Read Jackson Default Typing for object containing a field of Map and JacksonPolymorphicDeserialization.
Disable the feature and you will get result identical to plain json.

The main difference i see is that in arrays you have an additional string element at index 0.
If you always get the same structure you can do like this:
function jacksonToJson(jackson) {
jackson.removedVertices.splice(0, 1);
jackson.removedVertices.forEach((rmVert) => {
rmVert.info.splice(0, 1);
});
return jackson;
}

Related

Dynamically add array elements to JSON Object

I'm creating a JSON object from an array and I want to dynamically push data to this JSON object based on the values from array. See my code for a better understanding of my problem...
for(i=0;i<duplicates.length; i++) {
var request = {
"name": duplicates[i].scope,
"id": 3,
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
I take object properties from the duplicates array that can have the following elements:
[{scopeDef=.*, scope=Global, variable=[trackingcode, v1, v2]}, {scopeDef=^https?://([^/:\?]*\.)?delta.com/products, scope=Products Section, variable=[v3]}]
As you can see, an object contain variable element that can have multiple values. I need to push to the JSON object all those values dynamically (meaning that there could be more than 3 values in an array).
For example, after I push all the values from the duplicates array, my JSON object should look like this:
name=Products Section,
rules=
[
{
name=Products Section OP SDR Sync,
tags=[
{
variables=
[
{
matchType=Regex,
variable=v3,
value=^https?://([^/:\?]*\.)?delta.com/products
},
{
matchType=Regex,
variable=trackingcode,
value=.*
},
{
matchType=Regex,
variable=v1,
value=.*
},
{
matchType=Regex,
variable=v2,
value=.*
}
],
condition=false,
},
{
condition=false,
tagId=1
}
],
ruleSetId=3
}
]
}
I tried the following code but without success:
for(var j in duplicates[i].variable) {
var append = JSON.parse(request);
append['variables'].push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
}
Please let me know if I need to provide additional information, I just started working with JSON objects.
First of all, you dont need to parse request, you already create an object, parse only when you get JSON as string, like:
var json='{"a":"1", "b":"2"}';
var x = JSON.parse(json);
Next, you have any property of object wrapped in arrays. To correctly work with it you should write:
request.rules[0].tags[0].variables.push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
If you want to use your code snippet, you need some changes in request:
var request = {
"name": duplicates[i].scope,
"id": 3,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
To understand JSON remember basic rule: read JSON backward. It means:
property
object.property
arrayOfObfects['id'].object.property
mainObject.arrayOfObfects['id'].object.property
and so on. Good luck!

How to escape commas in JSON for read by highchart

I have the following JSON, I want add commas in between the numbers, but when ever I do that the JSON fails. My workign version of the code can be seen in the fiddle link below
FIDDLE
I want to change this 11488897 to 11,488,897
Is this possible to do? How can this be done?
thanks for your help
[{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}]
If you want to preserve commas, you just need to use strings:
"data": ["48,353,330","38,079,817","37,130,929","1,957,317"]
Whether that's a good idea or not is another story. Typically you'd want your JSON returned by the server to include raw (i.e., integer) data, and then just format it however you want when you're actually using it. That way the same RPC endpoint can be used to fetch data for use in a chart or for any other purpose that might arise later on.
try this:
var data = [{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}];
data.forEach(function(obj) {
obj.data = obj.data.map(function(item) {
if (typeof item == 'number') {
return item.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return item;
}
});
});
alert(JSON.stringify(data, true, 4));
I don't know if it's cross-browser but if you do this
var number = 11488897;
number = number.toLocaleString('en');
You'll get the number (string) with commas on decimals

How to filter a JSON tree according to an attribute inside

I have to re-post this questions with more details again:
I got a JSON tree array.
The structure of JSON tree looks like this:
{
"app": {
"categories": {
"cat_222": {
"id": "555",
"deals": [{
"id": "73",
"retailer": "JeansWest"
}, {
"id": "8630",
"retailer": "Adidas"
}, {
"id": "11912",
"retailer": "Adidas"
}]
},
"cat_342": {
"id": "232",
"deals": [{
"id": "5698",
"retailer": "KFC"
}, {
"id": "5701",
"retailer": "KFC"
}, {
"id": "5699",
"retailer": "MC"
}]
}
}
}
}
now, I'd like to filter this JSON tree with var pattern="KF",
return all with retailer name contains KF with it's id.
======================update===========================
Just check my other question. It got solved.
filter multi-dimension JSON arrays
Use Array.filter or _.filter if you need to support IE < 9
Well, you can use _.filter:
var filteredArray = _.filter(arrayOfStrings, function(str) {
return str.indexOf(data) !== -1; });
... or jQuery.grep:
var filteredArray = $.grep(arrayOfStrings, function(str) {
return str.indexOf(data) !== -1; });
As you see, the approaches are quite similar - and, in fact, both use Array.filter, if it's available in the host environment.
Also note that the original array is not affected here. If you want otherwise, just assign the result of filtering to the same variable (i.e., arrayOfStrings in this example).

Accessing JavaScript Sub-properties by Name

I wrote the following JavaScript function (part of a larger "class") to help ensure anybody using the object stores attribute values in the "values" property.
function _updateAttributes(attribute, value) {
_attributes[attribute] = { values: { value: value }};
}
It works fine for a flat structure, but falls apart when I start trying to use it for sub-properties.
After running the following code:
myEntity.updateAttribute('name', 'Frankenstein');
myEntity.updateAttribute('name.source', 'John Doe');
I'd like the following structure:
{
"attributes": {
"name": {
"values": {
"value": "Frankenstein"
},
"source": {
"values": {
"value": "JohnDoe"
}
}
}
}
}
Instead, it's coming out like this:
{
"attributes": {
"name": {
"values": {
"value": "Frankenstein"
}
},
"name.source": {
"values": {
"value": "JohnDoe"
}
}
}
}
Is there any clean way to write this JavaScript or will I be faced with splitting out the strings and manually building the structure?
NOTE: I realize even the preferred structure is a little odd, but there's a Java object I'm mapping to that expects this format, so I don't have any options here.
You'll have to parse the string (parse is a bit strong, just a single split('.') with a loop).
But frankly, the cleaner way would simply be:
myEntity.name = {values: 'Frankenstein'};
myEntity.name.source = {values: 'John Doe'};

How to retrieve value from json output?

I am new to json. I have json output that looks like this
[
{
"employees": {
"education": "BE\/B.Tech"
},
"0": {
"count": "1"
}
},
{
"employees": {
"education": "MBA"
},
"0": {
"count": "3"
}
}
]
I want to retrieve the employee's education and the count. I have tried but i am not able to retrieve the values.
I appreciate any help.
Thanks.
Assuming your JSON string is in a variable $json, it goes like this:
var employees_list = JSON.parse($json);
Then you can access the information via:
employees_list[0].employees.education // gives you "BE\/B.Tech"
// and
employees_list[0]["0"].count // gives you 1.
You can also loop over the array and access all the different education this way.
Update:
To better demonstrate which expression accesses which information:
[ // employees_list
{ // employees_list[0]
"employees": { // employees_list[0].employees
"education": "BE\/B.Tech" // employees_list[0].employees.education
},
"0": { // employees_list[0]["0"]
"count": "1" // employees_list[0]["0"].count
}
},
{ // employees_list[1]
"employees": { // employees_list[1].employees
"education": "MBA" // employees_list[1].employees.education
},
"0": { // employees_list[1]["0"]
"count": "3" // employees_list[1]["0"].count
}
}
]
Generally employees_list[0].employees is the same as employees_list[0]["employees"] but this does not work for numbers, because properties and variables are not allowed to start with numbers. So you can only use employees_list[0].["0"] and not employees_list[0].0.
The structure of your JSON string looks a bit strange though. You should consider to structure it differently if you can.
For example:
[
{
"education": "BE\/B.Tech",
"count": "1"
},
{
"education": "MBA"
"count": "3"
}
]
The "0" key in your original JSON string seems to serve no purpose and just complicates the access.

Categories

Resources