Parsing JSON converted XML in Javascript - javascript

I am building an API that send a SOAP request to a web service in express, i used easy-soap-request to send SOAP request and naturally i got an XML response, then i used xml2js to convert the response. This was the response:
{
"s:Envelope": {
"$": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"s:Body": [
{
"SmartSearchIndividualResponse": [
{
"$": {
"xmlns": "some-url"
},
"SmartSearchIndividualResult": [
{
"$": {
"xmlns:a": "yet-another-url",
"xmlns:i": "http://www.w3.org/2001/XMLSchema-instance"
},
"a:IndividualRecords": [
{
"a:SearchIndividualRecord": [
{
"a:Address": [
"person-address"
],
"a:DateOfBirth": [
"person-DOB"
],
"a:FullName": [
"person-full-name"
],
"a:IDNumber": [
"person-ID-number"
],
"a:CompID": [
"company-ID"
]
}
]
}
]
}
]
}
]
}
]
}
}
is there anyway to extract some data like address or full name?

very bad JSON structure
const data =
{ 's:Envelope':
{ '$': { 'xmlns:s': 'http://schemas.xmlsoap.org/soap/envelope/'}
, 's:Body':
[ { 'SmartSearchIndividualResponse':
[ { '$': { 'xmlns': 'some-url'}
, 'SmartSearchIndividualResult':
[ { '$':
{ 'xmlns:a': 'yet-another-url'
, 'xmlns:i': 'http://www.w3.org/2001/XMLSchema-instance'
}
, 'a:IndividualRecords':
[ { 'a:SearchIndividualRecord':
[ { 'a:Address': [ 'person-address' ]
, 'a:DateOfBirth': [ 'person-DOB' ]
, 'a:FullName': [ 'person-full-name' ]
, 'a:IDNumber': [ 'person-ID-number' ]
, 'a:CompID': [ 'company-ID' ]
} ] } ] } ] } ] } ] } }
let individualRecs = data['s:Envelope']['s:Body'][0]
.SmartSearchIndividualResponse[0]
.SmartSearchIndividualResult[0]
['a:IndividualRecords'][0]
['a:SearchIndividualRecord'][0]
console.log( individualRecs['a:Address'][0] )
console.log( individualRecs['a:FullName'][0] )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

MongoDB - Set field to hash of another field

Is there a way to run this query so that instead of { $toString: "$_id" } I can take the hash of the image field value for that document and set the field to that hash value?
So instead of this:
db.getCollection("test_products").updateMany( {_id: {$in: [ ObjectId('6340eae3bb965cdee37b8b30'), ObjectId('6340eae3bb965cdee37b8b33') ]}}, [
{ $set : { image : { $concat : [ "https://www.example.com/products/", { $toString: "$_id" }, ".png" ] } } }
] );
I would want something like this:
db.getCollection("test_products").updateMany( {_id: {$in: [ ObjectId('6340eae3bb965cdee37b8b30'), ObjectId('6340eae3bb965cdee37b8b33') ]}}, [
{ $set : { image : { $concat : [ "https://www.example.com/products/", { $hex_md5: "$image" }, ".png" ] } } }
] );
You will need to use $function to use js functionality for the md5 sum computation.
db.collection.update({},
[
{
"$addFields": {
"image": {
"$function": {
"body": "function(image){return \"https://www.example.com/products/\"+hex_md5(image)+\".png\"}",
"args": [
"$image"
],
"lang": "js"
}
}
}
}
],
{
multi: true
})
Mongo Playground

How to return a nested JSon object in a key value store object

I have a [simplified] JSON file like
{
"id":87,
"meta_data":[
{
"id":1232,
"key":"user_created_by",
"value":"example#gmail.com"
},
{
"id":1233,
"key":"user_created_at",
"value":"1659890457477"
},
{
"id":1234,
"key":"good_person_or_silly_sausage",
"value":"No"
}
]
}
I want to do something like
Logger.log(orderDetailsObject.meta_data.value[key="good_person_or_silly_sausage"])
The expected value would be
No
However, this isn't what's occurring. At present I'm being told that the object is null.
I think it's because the meta_data object is an object in an object or two dimensional array or something? I don't have a good understand of what I'm doing here,
I feel like
https://docs.jsonata.org/simple
and
https://docs.jsonata.org/predicate
Should be guiding me towards the answer - but I'm not getting something I think.
I'm a newbie to SO and JSON & Javascript - so please be gentle. <3
EDIT: None-simplified actual json file below:
{
"id":87,
"parent_id":0,
"status":"pending",
"currency":"USD",
"version":"6.5.1",
"prices_include_tax":false,
"date_created":"2022-08-07T16:40:57",
"date_modified":"2022-08-11T10:13:07",
"discount_total":"0.00",
"discount_tax":"0.00",
"shipping_total":"0.00",
"shipping_tax":"0.00",
"cart_tax":"0.00",
"total":"1100.00",
"total_tax":"0.00",
"customer_id":17,
"order_key":"wc_order_omQo7nW5yCS9X",
"billing":{
"first_name":"",
"last_name":"",
"company":"",
"address_1":"",
"address_2":"",
"city":"",
"state":"",
"postcode":"",
"country":"",
"email":"freddie#example.com",
"phone":""
},
"shipping":{
"first_name":"",
"last_name":"",
"company":"",
"address_1":"",
"address_2":"",
"city":"",
"state":"",
"postcode":"",
"country":"",
"phone":""
},
"payment_method":"",
"payment_method_title":"",
"transaction_id":"",
"customer_ip_address":"",
"customer_user_agent":"",
"created_via":"rest-api",
"customer_note":"",
"date_completed":null,
"date_paid":"2022-08-07T16:40:58",
"cart_hash":"",
"number":"87",
"meta_data":[
{
"id":1232,
"key":"user_created_by",
"value":"example#gmail.com"
},
{
"id":1233,
"key":"user_created_at",
"value":"1659890457477"
},
{
"id":1234,
"key":"good_person_or_silly_sausage",
"value":"No"
},
{
"id":1235,
"key":"order_request_high_chair",
"value":"yes"
},
{
"id":1240,
"key":"order_notes",
"value":"They're on their honeymoon"
},
{
"id":1241,
"key":"pricing_notes",
"value":"They're on their honeymoon"
},
{
"id":1242,
"key":"order_booked_by",
"value":"me on me"
},
{
"id":1243,
"key":"order_referral_source",
"value":"Newspaper"
},
{
"id":1244,
"key":"commission_percent",
"value":"13"
},
{
"id":1245,
"key":"discount_percent",
"value":"5"
},
{
"id":1246,
"key":"deposit_paid_date",
"value":"today"
},
{
"id":1247,
"key":"damage_bond_date_paid",
"value":"today"
},
{
"id":1248,
"key":"damage_bond",
"value":"100"
},
{
"id":1249,
"key":"start_date",
"value":"01\/01\/01"
},
{
"id":1250,
"key":"deposit_payment_amount",
"value":"500"
},
{
"id":1251,
"key":"order_request_welcome_pack_wine_type",
"value":"Red"
},
{
"id":1252,
"key":"end_date",
"value":"02\/02\/02"
},
{
"id":1259,
"key":"_new_order_email_sent",
"value":"true"
},
{
"id":1260,
"key":"_automatewoo_order_created",
"value":"1"
}
],
"line_items":[
{
"id":45,
"name":"Villa Booking",
"product_id":0,
"variation_id":0,
"quantity":1,
"tax_class":"",
"subtotal":"1000.00",
"subtotal_tax":"0.00",
"total":"1000.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":411,
"key":"Dates",
"value":"01\/01\/01 until 02\/02\/02",
"display_key":"Dates",
"display_value":"01\/01\/01 until 02\/02\/02"
}
],
"sku":null,
"price":1000,
"parent_name":null
},
{
"id":46,
"name":"Standard Welcome Pack",
"product_id":73,
"variation_id":0,
"quantity":2,
"tax_class":"",
"subtotal":"0.00",
"subtotal_tax":"0.00",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":421,
"key":"Wine Type",
"value":"Red",
"display_key":"Wine Type",
"display_value":"Red"
}
],
"sku":"",
"price":0,
"parent_name":null
}
],
"tax_lines":[
],
"shipping_lines":[
],
"fee_lines":[
{
"id":47,
"name":"Damage Bond",
"tax_class":"",
"tax_status":"taxable",
"amount":"100",
"total":"100.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":428,
"key":"damage_bond_paid_to",
"value":"example#gmail.com",
"display_key":"damage_bond_paid_to",
"display_value":"example#gmail.com"
},
{
"id":429,
"key":"damage_bond_paid_on",
"value":"today",
"display_key":"damage_bond_paid_on",
"display_value":"today"
}
]
},
{
"id":48,
"name":"Booking Fee",
"tax_class":"",
"tax_status":"taxable",
"amount":"",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":436,
"key":"dbooing_fee_paid_to",
"value":"example#gmail.com",
"display_key":"dbooing_fee_paid_to",
"display_value":"example#gmail.com"
},
{
"id":437,
"key":"booking_fee_paid_on",
"value":"1659890457477",
"display_key":"booking_fee_paid_on",
"display_value":"1659890457477"
}
]
}
],
"coupon_lines":[
],
"refunds":[
],
"payment_url":"https:\/\/dev1.example.com\/checkout\/order-pay\/87\/?pay_for_order=true&key=wc_order_omQo7nW5yCS9X",
"date_created_gmt":"2022-08-07T16:40:57",
"date_modified_gmt":"2022-08-11T10:13:07",
"date_completed_gmt":null,
"date_paid_gmt":"2022-08-07T16:40:58",
"currency_symbol":"$",
"_links":{
"self":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/orders\/87"
}
],
"collection":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/orders"
}
],
"customer":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/customers\/17"
}
]
}
}
You can use the find method on the array:
const orderDetailsObject = {"id":87,"meta_data":[{"id":1232,"key":"user_created_by","value":"example#gmail.com"},{"id":1233,"key":"user_created_at","value":"1659890457477"},{"id":1234,"key":"good_person_or_silly_sausage","value":"No"}]};
console.log(orderDetailsObject.meta_data.find(
({key}) => key == "good_person_or_silly_sausage"
)?.value);

How to update subset of a string in MongoDB?

I want to update the following subset of a string in monogdb
Collection: Paper
Field: URL
Document Current:
Name : House
URL : www.home.com/300x300
Document Updated
Name : House
URL : www.home.com/600x600
I have already tried this but it doesn't seem to be working:
db.Paper.find({Name:"House"}).forEach(function(e,i) {
e.URL=e.URL.replace("300","600");
db.Paper.save(e);
});
Any ideas?
You can use one of the following aggregations to query and update:
db.test.aggregate( [
{
$match: {
url: { $regex: "300x300" }
}
},
{
$addFields: {
url: { $split: [ "$url", "300" ] }
}
},
{
$addFields: {
url: {
$concat: [
{ $arrayElemAt: [ "$url", 0 ] },
"600",
{ $arrayElemAt: [ "$url", 1 ] },
"600",
{ $arrayElemAt: [ "$url", 2 ] }
]
}
}
}
] ).forEach( doc => db.test.updateOne( { _id: doc._id }, { $set: { url: doc.url } } ) )
With MongoDB version 4.2+ you can specify the aggregation instead of an update operation with updateMany:
db.test.updateMany(
{
url: { $regex: "300x300" }
},
[
{
$addFields: {
url: { $split: [ "$url", "300" ] }
}
},
{
$addFields: {
url: {
$concat: [
{ $arrayElemAt: [ "$url", 0 ] },
"600",
{ $arrayElemAt: [ "$url", 1 ] },
"600",
{ $arrayElemAt: [ "$url", 2 ] }
]
}
}
}
]
)
Pretty simple, you have to use regex instead of string in the pattern of replace function as below:
> db.Paper.find({Name:"House"}).forEach(function (e, i) {e.URL = e.URL.replace(/300/g, "600"), printjson(e); db.Paper.save(e);} )
{
"_id" : ObjectId("5e016224a16075c5bd26fbe2"),
"Name" : "House",
"URL" : "www.home.com/600x600"
}
> db.Paper.find()
{ "_id" : ObjectId("5e016224a16075c5bd26fbe2"), "Name" : "House", "URL" : "www.home.com/600x600" }
>
So, there is a difference between e.URL.replace("300", "600") and e.URL.replace(/300/g, "600"). You should figureout it yourself.
For references, please go through this: https://flaviocopes.com/how-to-replace-all-occurrences-string-javascript/

How get informations in javascript from API JSON?

I need help ! Can you tell me how can I get informations from this in javascript :
I would like to get the Third values from the fisrt array (121,73) and also the Fourth (99,25) . Thank you in advance !
{
"error": [],
"result": {
"XETHZEUR": [
[
1545955200,
"100.76",
"121.73",
"99.25",
"120.16",
"111.15",
"186385.05723331",
25420
],
[
1546041600,
"120.52",
"130.00",
"115.91",
"117.89",
"121.47",
"154551.36751227",
23261
],
"last": 1546387200
}
}
var feild = {
"error": [],
"result": {
"XETHZEUR": [
[
1545955200,
"100.76",
"121.73",
"99.25",
"120.16",
"111.14",
"183581.25666187",
25053
],
[
1546041600,
"120.16",
"130.00",
"115.91",
"117.89",
"121.48",
"152980.08236398",
21309
],
[
1546128000,
"117.96",
"123.75",
"112.78",
"121.99",
"119.43",
"108719.51659796",
14936
],
[
1546214400,
"121.99",
"122.30",
"113.00",
"114.96",
"118.14",
"69796.43117029",
9347
],
[
1546300800,
"114.97",
"123.90",
"114.00",
"122.46",
"119.83",
"64248.31302812",
9713
],
[
1546387200,
"122.62",
"138.80",
"121.25",
"135.57",
"131.69",
"189734.68299147",
37935
],
[
1546473600,
"135.57",
"136.25",
"128.33",
"131.45",
"132.12",
"67066.92874540",
8790
]
],
"last": 1546387200
}
}
let empty= [];
feild.result.XETHZEUR.map(e=>{
empty.push(e[2])
empty.push(e[3])
})
empty.map(e=>{
if(e=="121.73"){
console.log(e)
}
if(e=="99.25"){
console.log(e)
}
})

JSON parser with Array Comma Separated Javascript

i have a JSON structure which looks like this.
"content" : {
"state" : {
"Idle" : [
[
78.366666667,
1436955825
],
[
71.281111111,
1436955840
],
[
70.41,
1436955855
],
[
74.283333333,
1436955870
],
[
76.411111111,
1436955885
]
]
} }
What i have to do is to parse this value. i have to separate comma separated value into x and y. i have to parse these values and separate them. i am having problem issue parsing them
it should look like this
"Idle" : [
{
"x" : 78.366666667,
"y" :1436955825
},
{
"x" :71.281111111,
"y" :1436955840
},
{
"x" :70.41,
"y" :1436955855
},
{
"x" :74.283333333,
"y" :1436955870
},
{
"x" :76.411111111,
"y" :1436955885
}
]
Map the ...Idle elements to objects (see MDN for Array.map):
test = {
content: {
state: {
Idle: [
[
78.366666667,
1436955825
],
[
71.281111111,
1436955840
],
[
70.41,
1436955855
],
[
74.283333333,
1436955870
],
[
76.411111111,
1436955885
]
]
}
}
};
test.content.state.Idle = test.content.state.Idle.map(
function (v) {
return { x: v[0], y: v[1] };
}
);
document.querySelector("#result").textContent = JSON.stringify(test, null, " ");
<pre id="result"></pre>
var container = {
"content": {
"state": {
"Idle": [
[
78.366666667,
1436955825
],
[
71.281111111,
1436955840
],
[
70.41,
1436955855
],
[
74.283333333,
1436955870
],
[
76.411111111,
1436955885
]
]
}
}
};
var _oldIdle = container.content.state.Idle,
_newIdle = [];
for (var i = 0; i < _oldIdle.length; i++) {
_newIdle.push({
x: _oldIdle[i][0],
y: _oldIdle[i][1]
});
}
container.content.state.Idle = _newIdle;
Try this way:
var json = {
"content": {
"state": {
"Idle": [
[
78.366666667,
1436955825
],
[
71.281111111,
1436955840
],
[
70.41,
1436955855
],
[
74.283333333,
1436955870
],
[
76.411111111,
1436955885
]
]
}
}
};
var newObj = {},
arr = [];
$.each(json.content.state.Idle, function(i, item) {
arr.push({x: item[0], y: item[1]});
});
newObj.idle = arr;
console.log(newObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you have JSON string you can use JSON.parse with reviver function
var json = '{"content":{"state":{"Idle":[[78.366666667,1436955825],[71.281111111,1436955840],[70.41,1436955855],[74.283333333,1436955870],[76.411111111,1436955885]]}}}';
var result = JSON.parse(json, function(k, v) {
if ((v instanceof Array) && (isFinite(Number(k)))) {
//if array with coordinates - return object instead
return {
x: v[0],
y: v[1]
};
}
return v;
})
console.log(result);
document.getElementById('r').innerHTML = JSON.stringify(result,null,2)
<pre id='r'></pre>
With UnderscoreJS is simple:
JSFiddle
var values = {
"content": {
"state": {
"Idle": [
[
78.366666667,
1436955825],
[
71.281111111,
1436955840],
[
70.41,
1436955855],
[
74.283333333,
1436955870],
[
76.411111111,
1436955885]
]
}
}
};
var newValues = _.map(values.content.state.Idle, function (value, key) {
return {x: value[0], y: value[1]};
});
console.log(newValues);

Categories

Resources