Lodash : Extent by adding to attribute - lodash

[
{
"Office_Id": 100,
"Address1": "xxxxx",
"Address2": "",
"City": "ANNISTON",
"District_Id": 1277,
"OfficeName": "test"
},
{
"Office_Id": 200,
"Address1": "xxxxx",
"Address2": "",
"City": "ANNISTON",
"District_Id": 1277,
"OfficeName": "test"
},
{
"Office_Id": 300,
"Address1": "xxxxx",
"Address2": "",
"City": "ANNISTON",
"District_Id": 1277,
"OfficeName": "test"
}
]
Using lodash how can i add a new attribute by combining Office_Id And OfficeName
{
"Office_Id": 300,
"Address1": "xxxxx",
"Address2": "",
"City": "ANNISTON",
"District_Id": 1277,
"OfficeName": "offce_ttttt",
"office": "300 - offce_ttttt"
}

In mutating the original objects:
offices = _.forEach(offices, function (o) {
_.assign(o, { office: o.Office_Id + ' - ' + o.OfficeName })
})
Without mutating the original objects:
var newObjects = _.map(offices, function (o) {
return _.assign({}, o, { office: o.Office_Id + ' - ' + o.OfficeName })
})

Related

Parsing Dynamic response in Karate

I want to verify the value of "RequestedName" in the following response, where the keys for different drugs is dynamic:
{
"requestId": "c826bee1-610e-4dee-b998-1fe4f8c15a1b",
"requestSource": "",
"responseSource": "client",
"status": 200,
"responseCodes": [
{
"code": "S00001",
"message": "Success.",
"params": {
"entity": ""
}
}
],
"context": null,
"payload": {
"0113ccf86ba79b698b8e7a8fb9effc4b": {
"RequestedName": "paracetamol",
"SearchKey": "0113ccf86ba79b698b8e7a8fb9effc4b",
"Name": "Genexa Acetaminophen Extra Strength",
"PrescribableName": "",
"ProductCodes": [
"69676-0059"
],
"DosageForm": "Tablet, coated",
"Route": "Oral",
"Approved": false,
"UnApproved": false,
"Generic": false,
"Allergen": false,
"Vaccine": false,
"Strength": {
"Number": "500",
"Unit": "mg/1"
},
"Purposes": {},
"SideEffects": {}
},
"0349fa4ea29da419c46745bc7e2a6c07": {
"RequestedName": "paracetamol",
"SearchKey": "0349fa4ea29da419c46745bc7e2a6c07",
"Name": "Pain Reliever",
"PrescribableName": "",
"ProductCodes": [
"70677-0168"
],
"DosageForm": "Tablet, extended release",
"Route": "Oral",
"Approved": true,
"UnApproved": false,
"Generic": true,
"Allergen": false,
"Vaccine": false,
"Strength": {
"Number": "650",
"Unit": "mg/1"
},
"Purposes": {},
"SideEffects": {}
},
"060cfbde5d82d947c56aac304c136fd3": {
"RequestedName": "paracetamol",
"SearchKey": "060cfbde5d82d947c56aac304c136fd3",
"Name": "Betr Pain Relief",
"PrescribableName": "Acetaminophen 500 mg Oral Tablet",
"ProductCodes": [
"80267-0484"
],
"DosageForm": "Tablet",
"Route": "Oral",
"Approved": false,
"UnApproved": false,
"Generic": false,
"Allergen": false,
"Vaccine": false,
"Strength": {
"Number": "500",
"Unit": "mg/1"
},
"Purposes": {},
"SideEffects": {}
},
"0950fcbac262c1c1d3a9e6630615a5f9": {
"RequestedName": "paracetamol",
"SearchKey": "0950fcbac262c1c1d3a9e6630615a5f9",
"Name": "Acetaminophen",
I tired this:
* def list = []
* def fun = function(k, v){ karate.appendTo('list', { key: k, val: v } )}
* karate.forEach(response, fun)
* def keys = $list[?(#.val.payload.RequestedName==drugName)].key
but not working, getting error as below:
def keys = $list[?(#.val.payload.RequestedName==drugName)].key
Failed to parse filter: [?(#.val.payload.RequestedName==drugName)], error on position: 32, char: d
testsuite/GetDrugs.feature:20
Here is the approach you can use:
* def response =
"""
{
dynamicKey1: {
fixedKey: 'fixedValue1',
dataKey: 'dataValue2'
},
dynamicKey2: {
fixedKey: 'fixedValue2',
dataKey: 'dataValue2'
}
}
"""
* def keys = []
* def fun = function(k, v){ if (v.fixedKey == 'fixedValue2') keys.push(k) }
* karate.forEach(response, fun)
* match keys == ['dynamicKey2']

How to get values from an array of objects using a KEY and creating a new array of values with LODASH

I have this array of Objects (it's a snippet of greater city, state, zip
[{
"city": "Picardville",
"state": "MA",
"zip": "11119"
},{
"city": "Picardville",
"state": "MA",
"zip": "11120"
},
{
"city": "Kirktown",
"state": "MA",
"zip": "11121"
},
{
"city": "Janewayville",
"state": "MA",
"zip": "11122"
},
{
"city": "Kahnville",
"state": "MA",
"zip": "11123"
}
]
So, if I push in a ZIP CODE, I want to make a new array that will SHOW all the cities for a ZIP and the STATE...Because cities can have multiple zipcodes, let's say I push in 11219, I would ONLY get the first one, but, if I enter PICARDVILLE in the CITY field, the ZIP codes that I can only choose from are: 11119 and 11120. The state would default to MA.
My thought is, without using Google Maps or Smarty Streets, my company wants me to do it this way. I've DONE it before with AngularJS back in 2016 but that was using uib-typeahead which is gone.
My code for Autopopulating CITY and STATE with ZIP code being entered is this.
autoSetCity(zip: string): string {
let cityname = '';
_.forOwn(citystatezip, function (value: any, key: any) {
if (value.zip_code === zip) {
cityname = value.city;
return;
}
});
console.log('CityName: ' + cityname);
return cityname;
}
autoSetState(zip: string): string {
let statename = '';
_.forOwn(citystatezip, function (value: any, key: any) {
if (value.zip_code === zip) {
statename = value.state;
return;
}
});
console.log('CityName: ' + statename);
return statename;
}
But it doesn't.
BTW, citystatezip is HUGE and contains all the CITIES, STATES, ZIPS, COUNTIES and LAT LONs for every ZIP code.
here's a sample:
{
"zip_code": 76465,
"latitude": 32.215275,
"longitude": -98.207997,
"city": "Morgan Mill",
"state": "TX",
"county": "Erath"
},
{
"zip_code": 76466,
"latitude": 32.442088,
"longitude": -98.734228,
"city": "Olden",
"state": "TX",
"county": "Eastland"
},
{
"zip_code": 76467,
"latitude": 32.341365,
"longitude": -97.932083,
"city": "Paluxy",
"state": "TX",
"county": "Hood"
},
I figured it out;
Here's my SERVICE layer
getCitiesAndStateBasedOnzip(zip: any): any {
const self = this;
let csz = this.allCityStateZip.data;
console.log('CSZ: ', csz);
for (let i = 0; i < csz.length; i++) {
if (csz[i].zip_code === zip * 1) {
self.cszctylatlon.city = csz[i].city;
self.cszctylatlon.state = csz[i].state;
self.cszctylatlon.county = csz[i].county;
self.cszctylatlon.country = 'USA';
self.cszctylatlon.zip = csz[i].zip_code;
self.cszctylatlon.lat = csz[i].latitude;
self.cszctylatlon.lon = csz[i].longitude;
}
}
console.log('Reduced City, State, Zip Object: ', this.cszctylatlon);
return this.cszctylatlon;
}
Here's where I get the info calling the service layer from the component
if (event.target.name === 'homezip') {
let zip = '';
zip = this.theform.value.homezip;
if (zip) {
let result = this.vaForm21elementService.getCitiesAndStateBasedOnzip(zip);
this.theform.patchValue({'homecity': result.city});
this.theform.patchValue({'homeprovince': result.county});
this.theform.patchValue({'homestate': result.state});
this.theform.patchValue({'homelat': result.lat});
this.theform.patchValue({'homelon': result.lon});
this.theform.patchValue({'homecountry': result.country});
this.theform.patchValue({'homeaddress': this.theform.value.homeaddressline1 + ' ' + this.theform.value.homeaddressline2 + ' ' + this.theform.value.homeaptnumber + ' ' + this.theform.value.homecity + ', ' + this.theform.value.homestate + ' ' + this.theform.value.homezip})
} else {
this.errmsg = 'No ZIP CODE Given';
console.log(this.errmsg);
return;
}
}
That's pretty much it.
I used TYPEAHEAD for the zip code and populate, CITY, STATE, COUNTY, LAT LON, and COUNTRY.
DONE!

How to update every object inside a JSON array with PostgreSQL?

I am trying to make a query that updates all the objects inside the nested json array i.e update first_name of all the people named 'John' to some other name.
My JSON is something like this but with way more data ofc:
{
"_id": {
"$oid": "5eb21a9f779aac987b2584b2"
},
"name": "Bouchard Restaurant and Inn",
"cuisine": "Australian",
"stars": 0.2,
"address": {
"street": "1602 Bosup Terrace",
"city": "Sibharze",
"state": "CA",
"zipcode": "21875"
},
"reviews": [
{
"person": {
"_id": {
"$oid": "57d7a121fa937f710a7d486e"
},
"address": {
"city": "Burgessborough",
"street": "83248 Woods Extension",
"zip": "47201"
},
"birthday": {
"$date": "2011-03-17T11:21:36Z"
},
"email": "murillobrian#cox.net",
"first_name": "Yvonne",
"job": "Counselling psychologist",
"last_name": "Pham"
},
"comment": "Aliquam est reiciendis alias neque ad.",
"created_on": {
"$date": "2017-12-09T20:49:00.35Z"
}
},
{
"person": {
"_id": {
"$oid": "57d7a121fa937f710a7d486f"
},
"address": {
"city": "Nicholsbury",
"state": "Indiana",
"street": "699 Ryan Branch Apt. 371",
"zip": "52277"
},
"birthday": {
"$date": "2015-11-25T17:26:40Z"
},
"email": "cindy93#gmail.com",
"first_name": "Mary",
"job": "Conservator, furniture",
"last_name": "Nelson"
},
"comment": "Quis sed tenetur eius illo.",
"created_on": {
"$date": "2020-01-03T16:55:51.396Z"
}
},
{
"person": {
"_id": {
"$oid": "57d7a121fa937f710a7d4870"
},
"address": {
"city": "Crystalmouth",
"street": "3924 Mosley Burg Suite 602",
"zip": "14969"
},
"birthday": {
"$date": "2015-04-07T19:10:04Z"
},
"email": "harrissummer#hotmail.com",
"first_name": "Jenna",
"job": "Engineer, land",
"last_name": "Smith"
},
"comment": "Recusandae rem minus dolorum corporis corrupti rem placeat.",
"created_on": {
"$date": "2019-06-13T13:00:34.473Z"
}
},
{
"person": {
"_id": {
"$oid": "57d7a121fa937f710a7d4871"
},
"address": {
"city": "Lake Meaganton",
"state": "Idaho",
"street": "2831 Kevin Knolls",
"zip": "10914-3394"
},
"birthday": {
"$date": "2014-02-08T01:03:22Z"
},
"email": "ythompson#hotmail.com",
"first_name": "Christopher",
"job": "Investment banker, corporate",
"last_name": "Franklin"
},
"comment": "Id provident eius natus quasi minima nobis.",
"created_on": {
"$date": "2016-01-05T02:15:06.933Z"
}
},
{
"person": {
"_id": {
"$oid": "57d7a121fa937f710a7d4872"
},
"address": {
"city": "Morganport",
"state": "Vermont",
"street": "9069 Bailey Ferry Suite 423",
"zip": "99473"
},
"birthday": {
"$date": "2015-12-19T18:27:42Z"
},
"email": "elizabeth35#mccarty.com",
"first_name": "Elizabeth",
"job": "Theatre stage manager",
"last_name": "Herrera"
},
"comment": "Sit perferendis nostrum suscipit cumque mollitia.",
"created_on": {
"$date": "2016-09-27T15:47:22.458Z"
}
}
]}
I have a query that updates the first object in the array successfully:
UPDATE restaurants
SET info = jsonb_set(info::jsonb, '{reviews,0,person,first_name}', '"Vedat"', true)
WHERE info->'reviews'->0->'person'->>'first_name' = 'John';
However, trying make an update query that updates all objects within the array (reviews) seems to be almost impossible.
I tried something like this:
UPDATE restaurants r
SET info = (
SELECT jsonb_agg(jsonb_set(rev::jsonb, '{first_name}', rev -> 'person' ->> 'first_name' = '"Vedat"', false))
FROM jsonb_array_elements(r.info::jsonb->'reviews') rev
WHERE rev -> 'person' ->> 'first_name' = 'John'
);
But it wasn't successful, it gives me errors like:
ERROR: function jsonb_set(jsonb, unknown, boolean, boolean) does not exist
UPDATE
I came up with this query but it runs inifitely
with rev as (
select id, generate_series(0, jsonb_array_length(info::jsonb->'reviews')-1) i
from restaurants
)
update restaurants r
set info = jsonb_set(r.info::jsonb,
array['reviews', rev.i::varchar, 'first_name'],
'"Vedat"'::jsonb)
from rev
where r.info->'reviews'->rev.i-> 'person' ->> 'first_name' = 'John'
The query gets a bit complicated but here is a solution, unless it matters that the order of elements in the .reviews array is not preserved:
update test_j
set j = jsonb_set( -- Replace the '.reviews' array with a concatenation of two arrays,
-- one with the unchanged objects and one with the changed ones.
j
, '{reviews}'
, jsonb_path_query_array( -- Extract the objects from the '.reviews' array
-- that need _no_ updating.
-- Uses the SQL/JSON Path Language.
j
, '$.reviews[*] ? (#.person.first_name != "Jenna" && #.person.first_name != "Yvonne")'
)
|| array_to_json(ARRAY( -- convert 'set of jsonb' to PostgreSQL array and back
-- ( do not forget the cast from json to jsonb !)
select jsonb_set( -- Update the json data
jsonb_path_query( -- Select the objects from the '.reviews' array
-- that need updating
-- (2 names chosen to demonstrate multiple updates
-- with the original sample data).
j
, '$.reviews[*] ? (#.person.first_name == "Jenna" || #.person.first_name == "Yvonne")'
)
, '{person,first_name}'
, '"Vedat"'
, true
)
from test_j
))::jsonb
, true
)
;
Most likely there are more elegant and more efficient ways to get the job done but the code should get people started.
Online demo available here (DB fiddle).
The relevant section of the PostgreSQL 12 docs can be found here

Issue when sending Query with Arabic characters through API

I can't send Query with Arabic characters through API. I am trying to send the query from CS-Cart to Quickbooks Online.
I tried to send the query using the arabic letters as the following:
select * from Customer Where DisplayName = 'احمد عبدالعزيز'
it returns:
{
"responseHeader": {
"status": 400,
"message": "Bad Request",
"intuitTid": "2dbec1fd-5dc1-3a14-4a12-7c338db0ee2a",
"realmID": "123146420719144"
},
"response": {
"Fault": {
"Error": [
{
"Message": "Error parsing query",
"Detail": "QueryParserError: Invalid content. Lexical error at line 1, column 45. Encountered: \"\\u0627\" (1575), after : \"\\'\"",
"code": "4000"
}
],
"type": "ValidationFault"
},
"time": "2019-07-04T07:09:03.026-07:00"
}
}
And if I try it after encoding the name and send the query as the following:
select * from Customer Where DisplayName = '%D8%A7%D8%AD%D9%85%D8%AF+%D8%B9%D8%A8%D8%AF%D8%A7%D9%84%D8%B9%D8%B2%D9%8A%D8%B2'
it returns nothing:
{
"QueryResponse": {},
"time": "2019-07-04T07:09:42.698-07:00"
}
I am expecting to get like:
{
"QueryResponse": {
"Customer": [
{
"Taxable": false,
"BillAddr": {
"Id": "924",
"Country": "Saudi Arabia"
},
"ShipAddr": {
"Id": "925",
"Country": "Saudi Arabia"
},
"Job": false,
"BillWithParent": false,
"Balance": 157.5,
"BalanceWithJobs": 157.5,
"CurrencyRef": {
"value": "SAR",
"name": "Saudi Riyal"
},
"PreferredDeliveryMethod": "None",
"IsProject": false,
"domain": "QBO",
"sparse": false,
"Id": "577",
"SyncToken": "0",
"MetaData": {
"CreateTime": "2019-07-01T06:37:32-07:00",
"LastUpdatedTime": "2019-07-01T06:37:33-07:00"
},
"GivenName": "Ramil",
"FamilyName": "Gilaev",
"FullyQualifiedName": "Ramil Gilaev",
"DisplayName": "Ramil Gilaev",
"PrintOnCheckName": "Ramil Gilaev",
"Active": true,
"PrimaryPhone": {
"FreeFormNumber": "123456789"
}
}
],
"startPosition": 1,
"maxResults": 1
},
"time": "2019-07-05T02:12:35.562-07:00"
}
Also I noticed even if the Query is in English name, it results the same.
select * from Customer Where DisplayName = 'Ahmed Al-Khuraisir'
it results:
{
"QueryResponse": {},
"time": "2019-07-05T03:31:11.149-07:00"
}
Please check attached images.
Screenshot 1
Screenshot 2

Cannot access child value on Newtonsoft.Json.Linq.JProperty

I am trying to parse the json values from the following stream:
{"id": "tag:search.xxxxx.com,2005:xxxxxxxxxxx"}
{"body": "acordei (:"}
{"verb": "post"}
{"link": "http://xxxxx.com/rohanaf_/xxxxxxxxxx/xxxxxxxxx"}
{"generator": {
"link": "http://xxxxx.com",
"displayName": "web"
}}
{"postedTime": "2012-03-31T19:23:51.000Z"}
{"provider": {
"link": "http://www.xxxxx.com",
"displayName": "xxxxxx",
"objectType": "service"
}}
{"object": {
"summary": "acordei (:",
"id": "object:search.xxxxxx.com,2005:xxxxxxxxxxxx",
"link": "http://xxxxxxx.com/rohanaf_/statuses/xxxxxxxxxxxx",
"postedTime": "2012-03-31T19:23:51.000Z",
"objectType": "note"
}}
{"actor": {
"summary": "- namorada da #srtameiga fim. ♥",
"twitterTimeZone": "Brasilia",
"friendsCount": 197,
"location": {
"displayName": "Porto Alegre ",
"objectType": "place"
},
"link": "http://www.xxxxxxxxxx.com/rohanaf_",
"postedTime": "2010-03-31T20:12:49.000Z",
"image": "http://a0.twimg.com/profile_images/xxxxxxxxxxx/Foto1436_normal.jpg",
"links": [
{
"rel": "me",
"href": null
}
],
"listedCount": 3,
"id": "id:xxxxxxxxxxx.com:xxxxxxxxx",
"languages": [
"pt"
],
"utcOffset": "-10800",
"followersCount": 347,
"preferredUsername": "rohanaf_",
"displayName": ", feia ;$",
"statusesCount": 48412,
"objectType": "person"
}}
{
"xxxxxx_entities": {
"urls": [],
"hashtags": [],
"user_mentions": []
}}
{"objectType": "activity"}
{"source": {
"language": {
"value": "fr"
},
"matching_rules": [
{
"value": "lang:fr",
"tag": null
}
],
}}
I tried the following options using JSON.NET and works mostly but missing a couple of fields (source: and all its children including their children). ("source")("matching_rules")("tag") ..etc
Dim results as List(Of JToken) = jobj.Children().ToList
For each item as JProperty In results
item.CreateReader()
If item.name ="id" then
id = item.value
End If
If item.name ="actor" then
author = item.Value("displayName").ToString
End If
If item.name="source" then
Dim gList as IList(Of JToken)= item("matching_rules").Children.ToList
End If
Next
I am trying to get all the children values for that property name source. Now if I use JsonTextReader I can read through everything but this is tedious and prone to errors. Any suggestions appreciated.
I figured it out
If item.name = "source" then
searchterm = item.last.selecttoken("matching_rules").first.item("value").tostring
End if