Apply regex expression to a json response data - javascript

Scenario client make a GET request the response is in a JSON format like this one
var data = {
"enabled": true,
"state": "schedule",
"schedules": [
{
"rule": {
"start": "2014-06-29T12:36:26.000",
"end": "2014-06-29T12:36:56.000",
"recurrence": [
"RRULE:FREQ=MINUTELY"
]
},
"wifi_state_during_rule": "disabled",
"end_state": "enabled"
}
],
"calculated_wifi_state_now": "disabled",
"time_of_next_state_change": [
"2014-07-08T18:56:56.000Z",
"2014-07-08T18:57:56.000Z"
]
};
For the purpose of this example I stored the result in a variable called "data".
My regex Expressions is:
checkPattern = /"\w+\"(?=:)/ //all keys "keyname": ...
The basic ideia here its just to get the keynames besides being inside of and object or array...since the definition of keyname's in JSON is "keyname": that's why I'm trying to use the above regex expression.
I even thought about doing this with a recursive function but is not working.

You never should parse non-regular structures with regular expressions.
Just collect what you want from parsed json object.
Just run data = JSON.parse(json_string) for parse it
function getKeysRecursive(obj) {
var result = [];
for (var key in obj) {
result.push(key);
if (typeof obj[key] == 'object') {
result = result.concat(getKeysRecursive(obj[key]));
}
}
return result;
}
getKeysRecursive(({
"enabled": true,
"state": "schedule",
"schedules": [
{
"rule": {
"start": "2014-06-29T12:36:26.000",
"end": "2014-06-29T12:36:56.000",
"recurrence": [
"RRULE:FREQ=MINUTELY"
]
},
"wifi_state_during_rule": "disabled",
"end_state": "enabled"
}
],
"calculated_wifi_state_now": "disabled",
"time_of_next_state_change": [
"2014-07-08T18:56:56.000Z",
"2014-07-08T18:57:56.000Z"
]
}))
// ["enabled", "state", "schedules", "0", "rule", "start", "end", "recurrence", "0", "wifi_state_during_rule", "end_state", "calculated_wifi_state_now", "time_of_next_state_change", "0", "1"]
You can filter them, sort, exclude numeric keys... All what you need.

You wont need a regular expression for this . Javascript has a built in function to extract Object key names .
Example :
Use Object.keys();
var data = {
"enabled": true,
"state": "schedule",
"schedules": [
{
"rule": {
"start": "2014-06-29T12:36:26.000",
"end": "2014-06-29T12:36:56.000",
"recurrence": [
"RRULE:FREQ=MINUTELY"
]
},
"wifi_state_during_rule": "disabled",
"end_state": "enabled"
}
],
"calculated_wifi_state_now": "disabled",
"time_of_next_state_change": [
"2014-07-08T18:56:56.000Z",
"2014-07-08T18:57:56.000Z"
]
};
Then
console.log(Object.keys(data));
should print
["enabled","state","schedules","calculated_wifi_state_now","time_of_next_state_change"]
Proof: http://codepen.io/theConstructor/pen/zBpWak
Now all of your object keys are stored in an array ..
Hope this helps

This will give you all of the keys as the matches:
\"(\w+)(?:\"\:)
https://regex101.com/r/iM9wB3/2
Edited to work with multiple keys on one line.

Related

jquery returning json data as undefined and images are not loading

I am trying to gain access within the last array of the json file and return the value from the "data" array of the json file and put it into the choiceSelection array. However, on my local host, it returns an undefined value and the images would not load. Can anyone help me out? I apologise if I haven't clearly explained my problem/logic and so please ask me for more details, if you're not sure. Thanks!
javascript code
$.getJSON('data.json', function(json) {
if(json[2].data){
for (i = 0; i < json[3].data.length; i++) {
choiceSelection[i] = new Array;
choiceSelection[i][0] = json[2].data[i].question;
choiceSelection[i][1] = json[2].data[i].correctChoice;
choiceSelection[i][2] = json[2].data[i].choice1;
choiceSelection[i][3] = json[2].data[i].choice2;
}
// choiceSelection.length = choiceSelection.length;
displayQuestion();
console.log(json[2]);
}
})
json file
[
{
"name": "match numbers 1",
"template": "matching",
"data": [
[
"six",
"Images/Number6.jpg"
],
[
"eight",
"Images/Number8.jpg"
],
[
"nine",
"Images/Number9.jpg"
]
]
},
{
"name": "order numbers 1",
"template": "ordering",
"data": [
[
"Images/Number6.jpg"
],
[
"Images/Number8.jpg"
],
[
"Images/Number9.jpg"
]
]
},
{
"name": "animal",
"template": "picture game",
"data": [
{
"question": "Where is the cat?",
"correctChoice": "Images/5cats.jpg",
"choice1": "Images/squirrel.png",
"choice2": "Images/beagle.png"
},
{
"question": "Where is the cat?",
"correctChoice": "Images/5cats.jpg",
"choice1": "Images/squirrel.png",
"choice2": "Images/beagle.png"
}
]
}
]
Edit 1: change json[i] to json[2].data. Still undefined
Edit 2: changed json[2].data. to json[2].data[i] and used json[3].data.length in the for statement. It works perfectly now. Thank you everyone for the help!:)
You could take the hassle out of your code and use some ES6 destructuring to get at your data more easily.
const json = '[{"name":"match numbers 1","template":"matching","data":[["six","Images/Number6.jpg"],["eight","Images/Number8.jpg"],["nine","Images/Number9.jpg"]]},{"name":"order numbers 1","template":"ordering","data":[["Images/Number6.jpg"],["Images/Number8.jpg"],["Images/Number9.jpg"]]},{"name":"animal","template":"picture game","data":[{"question":"Where is the cat?","correctChoice":"Images/5cats.jpg","choice1":"Images/squirrel.png","choice2":"Images/beagle.png"},{"question":"Where is the cat?","correctChoice":"Images/5cats.jpg","choice1":"Images/squirrel.png","choice2":"Images/beagle.png"}]}]'
function getJSON(endpoint, callback) {
setTimeout(() => callback(JSON.parse(json)), 1000);
}
// grab the third object from the response data
getJSON('data.json', function([ ,,obj ]) {
// grab the data array from that object but relabel it
// `choiceSelection
const { data: choiceSelection } = obj;
// then use the object property keys to get access
// to the data instead of indexes. Much easier.
console.log(choiceSelection[0].question);
console.log(choiceSelection[1].question);
});

Query Comparing Arrays of Objects

I'm wondering how I can compare arrays of (nested) objects in Mongoose.
Considering the data below, I would like to get results when the name properties match. Could anyone help me with this?
Organisation.find( {
$or: [
{ "category_list": { $in: cat_list } },
{ "place_topics.data": { $in: place_tops } }
]
}
)
Let's say that this is the data stored in my MongoDB:
"category_list": [
{
"id": "197750126917541",
"name": "Pool & Billiard Hall"
},
{
"id": "197871390225897",
"name": "Cafe"
},
{
"id": "218693881483234",
"name": "Pub"
}
],
"place_topics": {
"data": [
{
"name": "Pool & Billiard Hall",
"id": "197750126917541"
},
{
"name": "Pub",
"id": "218693881483234"
}
]
}
And let's say that these are the arrays I want to compare against (almost the same data):
let cat_list = [
{
"id": "197750126917541",
"name": "Pool & Billiard Hall"
},
{
"id": "197871390225897",
"name": "Cafe"
},
{
"id": "218693881483234",
"name": "Pub"
}
]
let place_tops = [
{
"name": "Pool & Billiard Hall",
"id": "197750126917541"
},
{
"name": "Pub",
"id": "218693881483234"
}
]
When there are "multiple conditions" required for each array element is when you actually use $elemMatch, and in fact "need to" otherwise you don't match the correct element.
So to apply multiple conditions, you would rather make an array of conditions for $or instead of shortcuts with $in:
Organizations.find({
"$or": [].concat(
cat_list.map( c => ({ "category_list": { "$elemMatch": c } }) ),
place_tops.map( p => ({ "place_topics": { "$elemMatch": p } }) )
)
})
However, if you take a step back and think logically about it, you actually named one of the properties "id". This would generally imply in all good practice that the value is in fact ""unique".
Therefore, all you really should need to do is simply extract those values and stick with the original query form:
Organizations.find({
"$or": [
{ "category_list.id": { "$in": cat_list.map(c => c.id) } },
{ "place_topics.id": { "$in": place_tops.map(p => p.id) } }
]
})
So simply mapping both the values and the property to "match" onto the "id" value instead. This is a simple "dot notation" form that generally suffices when you have one condition per array element to test/match.
That is generally the most logical approach given the data, and you should apply which one of these actually suits the data conditions you need. For "multiple" use $elemMatch. But if you don't need multiple because there is a singular match, then simply do the singular match

getting a specific value from JSON array with multiple arrays inside in javascript

I'm asking here as I can see this website the most one can help in this
I have an output value in JASON format as the following:
{
"total": 16,
"members": [{
"id": 4,
"name": "Blade11",
"descriptors": {
"os": "Windows 2012 / WS2012 R2"
},
"FCPaths": [{
"wwn": "50060B0000C27208",
"hostSpeed": 0
}, {
"wwn": "50060B0000C2720A",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 11,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 11\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}, {
"id": 6,
"name": "Blade4",
"descriptors": {
"os": "VMware (ESXi)"
},
"FCPaths": [{
"wwn": "50060B0000C27216",
"hostSpeed": 0
}, {
"wwn": "50060B0000C27214",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 8,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 8\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}
what I want is, to parse this output for retrieving an output parameter with the name object only in a list or array of string
for example Names = Blade11, Blade4,....
if you can see in the Json output we have all the names under "members", then each one is another array of values, I want to retrieve only names
thanks
If this JSON is string first you have to parse it
var json = JSON.parse('here is your JSON string');
Than you can access to it properties like you work with object
var names = json.members.map(function(member) {
return member.name;
});
Since you already have JSON format, you can use an array method on the member key of your JSON object to iterate through each array item.
var names = [];
object_name.members.forEach((arrItem) => {
names.push(arrItem.name);
}
or
namesArray = object_name.members.map((arrItem) => {
return arrItem.name;
}
You could use Array#map for iterating all elements of the array and return only the name property.
If you have a JSON string, you need to parse it in advance for getting an object, like
object = JSON.parse(jsonString);
var jsonString = '{"total":16,"members":[{"id":4,"name":"Blade11","descriptors":{"os":"Windows 2012 / WS2012 R2"},"FCPaths":[{"wwn":"50060B0000C27208","hostSpeed":0},{"wwn":"50060B0000C2720A","hostSpeed":0}],"iSCSIPaths":[],"persona":11,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 11\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false},{"id":6,"name":"Blade4","descriptors":{"os":"VMware (ESXi)"},"FCPaths":[{"wwn":"50060B0000C27216","hostSpeed":0},{"wwn":"50060B0000C27214","hostSpeed":0}],"iSCSIPaths":[],"persona":8,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 8\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false}]}',
object = JSON.parse(jsonString),
array = object.members.map(function (a) { return a.name; });
console.log(array);

Angular - Convert Jackson output to JSON

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

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!

Categories

Resources