convert json array to json object in laravel 5.7 - laravel

I am getting data from database using join query in laravel & pass to json and getting some result in array but I want object that I given below
Controller code:
$resultPastActivity= DB::table('table_user_create_activity')
->join('table_sub_category','table_user_create_activity.selected_activity_id', '=', 'table_sub_category.sub_category_id')
->select('sub_category_name','area','activity_type','activity_date','start_time','end_time')
->whereDate('activity_date', '<', $todayDate)
->where('user_id',$user_id)
->get();
return response()->json(['success' => '1','data' =>$resultPastActivity]);
The above code will give following json that is in array actually i want json in object
{
"success": "1",
"data": [
{
"sub_category_name": "Badminton",
"area": "Rankala lake",
"activity_type": "1",
"activity_date": "2018-01-12",
"start_time": "15:04:49",
"end_time": "20:05:69"
},
{
"sub_category_name": "Football",
"area": "Devakar panad",
"activity_type": "1",
"activity_date": "2018-01-15",
"start_time": "15:04:49",
"end_time": "20:05:69"
},
]
}
i want json as follows
{
"success": "1",
"data": {
{
"sub_category_name": "Badminton",
"area": "Rankala lake",
"activity_type": "1",
"activity_date": "2018-01-12",
"start_time": "15:04:49",
"end_time": "20:05:69"
},
{
"sub_category_name": "Football",
"area": "Devakar panad",
"activity_type": "1",
"activity_date": "2018-01-15",
"start_time": "15:04:49",
"end_time": "20:05:69"
},
}
}

try this, json_encode($json, JSON_FORCE_OBJECT) JSON_FORCE_OBJECT
$result=array();
$result["0"]=$resultPastActivity;
$json=json_encode((object)$result,JSON_FORCE_OBJECT);
return response()->json(['success' => '1','data' =>$json]);

The one you want is not a valid JSON, you can check it here: https://jsonformatter.curiousconcept.com/
So, you cannot create such an output, and, if you force it, the application that will receive it won't parse it correctly, so it doesn't make sense.

Related

Validation of each field in JSON response using karate API

I want to validate particular fields in the response whether it is integer or float(ex: fullbathrooms field). I tried below code but getting match failed error. Could you please help here ?.....Thanks
Given path '/property-client'
And request {"address": <address>,"city": <city>,"state": <state>,"zipCode": <zipCode>}
When method post
Then status 200
And print response
And match response == {fullbathrooms:'#number'}
Examples:
|read('testFile1.csv')|
Error : match failed: EQUALS
Actual response:
{
"success": true,
"message": {
"version": "1.0",
"response": {
"id": "94568859",
"type": "express",
"responseheader": null,
"reportdata": {
"property": {
"source": null,
"type": null,
"dom": null,
"propertytype": "Single Family Residence",
"standardtype": null,
"address": {
"documentid": null,
"number": "150",
"directional": null,
"street": "BRIDGE",
"suffix": "RD",
"postdirectional": null,
"unit": "",
"city": "HILLSBOROUGH",
"state": "CA",
"zip": "94010",
"zipplus4": "6908",
"fulladdress": "150 BRIDGE RD, HILLSBOROUGH, CA 94010"
},
"info": {
"type": null,
"fips": "6081",
"county": "San Mateo",
"bedrooms": "5",
"bathrooms": "6.50",
"fullbathrooms": "6.50",
"totalrooms": "0",
"livingarea": "7750",
"totallivingarea": "7750",
"landarea": "41382",
"landareatype": null,
"pool": "true",
"landvalue": "6904800",
"improvementvalue": "3284414",
"assessedvalue": "10189214",
"assessedyear": "2021",
"taxvalue": "11746898",
"taxyear": "2021",
"deliquentyear": null,
"yearbuilt": "2011",
"propertytax": null,
"approxage": "11",
"parcelnumber": "032-400-110",
"titlecompany": null,
"geocode": {
"latitude": "37.563272",
"longitude": "-122.334442",
"geoqualitycode": ""
}
}
Please take some time to read the documentation: https://github.com/karatelabs/karate#match-contains
I'm not going to refer to your response dump (which by the way is not valid JSON), but give you a simple example. Please pay attention to the structure of your JSON. And note that the 6.50 is a string not a number in your response.
* def response = { "foo": { "bar": { "fullbathrooms": "6.50" } } }
* match response.foo.bar == { fullbathrooms: '#string' }
If you want to validate numbers within strings, please refer other answers, for example: https://stackoverflow.com/search?q=%5Bkarate%5D+number+regex

NiFi: ReplaceText alternatives to modify JSON

My NiFi application receives two kinda different types of JSON's.
First of them looks like:
[
{
"campaign": {
"resourceName": "customers/8952771329/campaigns/11381694617",
"status": "ENABLED",
"name": "Saint_Spring_Active Minerals_oct-nov_2020_trueview_skip_5766500views",
"id": "11381694617"
},
"metrics": {
"interactionEventTypes": [
"VIDEO_VIEW"
],
"clicks": "6",
"videoQuartileP100Rate": 0.44493171079034244,
"videoQuartileP25Rate": 0.9747718298919024,
"videoQuartileP50Rate": 0.7339309987701469,
"videoQuartileP75Rate": 0.5337562301767105,
"videoViewRate": 0.4471109114825628,
"videoViews": "27872",
"viewThroughConversions": "0",
"contentBudgetLostImpressionShare": 0.0000013066088274492382,
"contentImpressionShare": 0.0999,
"contentRankLostImpressionShare": 0.9001,
"conversionsValue": 0,
"conversions": 0,
"costMicros": "9338700950",
"ctr": 0.00009624947864865732,
"currentModelAttributedConversions": 0,
"currentModelAttributedConversionsValue": 0,
"engagementRate": 0,
"engagements": "0",
},
"segments": {
"device": "CONNECTED_TV",
"date": "2020-12-20"
}
}
]
And second:
[
{
"adGroup": {
"resourceName": "customers/5404177717/adGroups/110501283582",
"campaign": "customers/5404177717/campaigns/11628802542"
},
"metrics": {
"interactionEventTypes": [
"CLICK"
],
"clicks": "1",
"averageCpm": 95497428.02172929,
"gmailForwards": "0",
"gmailSaves": "0",
"gmailSecondaryClicks": "0",
"impressions": "4418",
"interactionRate": 0.00022634676324128565,
"interactions": "1"
},
"adGroupAd": {
"resourceName": "customers/5404177717/adGroupAds/110501283582~480227690139",
"status": "ENABLED",
"ad": {
"resourceName": "customers/5404177717/ads/480227690139",
"id": "480227690139",
"name": "20 sec perek"
},
"adGroup": "customers/5404177717/adGroups/110501283582"
},
"segments": {
"device": "DESKTOP",
"date": "2020-11-21"
}
}
]
I already have 2 tables in my database to save this data. I have an attribute table.name just to not create same block where's only table name is different.
My next block is FlattenJson. After this i'm using ReplaceText with search value (replacement value is empty string): (customers\\\/${client.customer.id}\\\/campaigns\\\/|customers\\\/${client.customer.id}\\\/adGroups\\\/).
Why this? From this line: "adGroup": "customers/5404177717/adGroups/110501283582" i only need last value 110501283582 as ad_group_id. And from this line: "campaign": "customers/5404177717/campaigns/11628802542" i only need 11628802542. ${client.customer.id} can be different, so i'm using EL features.
Also i need to change json value name adGroup to ad.group.id, for this i'm also using ReplaceText.
Can i do it faster without two ReplaceText processors?
Look at the following processors...I think using them can be an alternative:
JoltTransformJSON:
https://nifi.apache.org/docs/nifi-docs/components/org.apache.nifi/nifi-standard-nar/1.5.0/org.apache.nifi.processors.standard.JoltTransformJSON/
UpdateRecord:
https://nifi.apache.org/docs/nifi-docs/components/org.apache.nifi/nifi-standard-nar/1.5.0/org.apache.nifi.processors.standard.UpdateRecord/index.html

Sorting an array of objects based on object property

I have an array like so:
[
{
"name": "aabb",
"commit": {
"id": "1",
"message": "aabb ",
"committed_date": "2018-04-04T15:11:04.000+05:30",
"committer_name": "ak",
"committer_email": "ak#ak.in"
},
"protected": false
},
{
"name": "aacc",
"commit": {
"id": "2",
"message": "aacc ",
"committed_date": "2018-02-04T15:11:04.000+05:30",
"committer_name": "ak",
"committer_email": "ak#ak.in"
},
"protected": false
},
{
"name": "aadd",
"commit": {
"id": "3",
"message": "aadd ",
"committed_date": "2018-04-01T15:11:04.000+05:30",
"committer_name": "ak",
"committer_email": "ak#ak.in"
},
"protected": false
}
]
I need to sort this array based on committed_date. How do I do that?
Do I have to loop and write a custom sorting function or does Ruby offers something out-of-box?
Using sort_by
array.sort_by {|obj| obj.attribute}
Or more concise
array.sort_by(&:attribute)
In your case
array.sort_by {|obj| obj[:commit][:committed_date]}

How to Get specific embedded array from mongodb and append it with new document using mongodb c# driver

I want to get specific embedded array from mongodb document and add new document in that embedded array using "mongodb.Driver" .net driver.
am inserting doc as:
{
"_id": "5c41b5c6b0ce0437dc576c53",
"ProjectId": "234",
"OwnerId": "62",
"ProjectName": "proj4h46m",
"FileDetails": [
{
"TotalWord": "-1",
"RepeatedWord": "-1",
"TMWordCount": "-1",
"TranslationRequired": "-1",
"ParentFileName": "test",
"ChildFileName": "test_AR-SA",
"Status": "Newly Uploaded"
}
]
}
I expect to get "FileDetails" array from it and add new doc and update to mongodb. as shown below:
{
"_id": "5c41b5c6b0ce0437dc576c53",
"ProjectId": "234",
"OwnerId": "62",
"ProjectName": "proj4h46m",
"FileDetails": [
{
"TotalWord": "-1",
"RepeatedWord": "-1",
"TMWordCount": "-1",
"TranslationRequired": "-1",
"ParentFileName": "test",
"ChildFileName": "test_AR-SA",
"Status": "Newly Uploaded"
},
{
"TotalWord": "10",
"RepeatedWord": "3",
"TMWordCount": "12",
"TranslationRequired": "1",
"ParentFileName": "test2",
"ChildFileName": "test_AR-KSA",
"Status": "Newly Uploaded"
}
]
}
I got this by using below method:-
var query2 = Query.EQ(""ProjectId", "234");
var document=#"{""TotalWord"": ""10"",""RepeatedWord"": "3",""TMWordCount"": ""12"",""TranslationRequired"": ""1"",""ParentFileName"": ""test2"",""ChildFileName"": ""test_AR-KSA"",""Status"": ""Newly Uploaded""}";
var update = Update.Push("FileDetails", document.ToBsonDocument());
collec.Update(query2, update);

error given Sending json array in ajax request? using javascript

hihi i am doing a project regarding ajax (xmlHttRequest),
how am i going to call the title in the note session, because normally if you call start year is like, detail = eval....
then for loop it
inside should be
var start year=""
startyear += ...[i].startyear
something like this, but how am i going to call the title inside the note?
i try to call detail.notes.note.title it say is null or is not a object
this is json data:
{
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{
"id": "1",
"title": "Red House",
"url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html"
},
{
"id": "2",
"title": "Joo Chiat",
"url": "http://www.the-inncrowd.com/joochiat.htm"
},
{
"id": "3",
"title": "Bake",
"url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery"
}
]
}
]
}
}
Use http://jsonlint.com/ to help you out with JSON.
I got this...
Parse error on line 30:
... ] }
----------------------^
Expecting '}', ',', ']'

Resources