Remove proxies from Json Response Symfony2 - json

I'm working in Symfony2 application and what I'm trying to do is to remove unwanted fields from response and show only fields that I want.
My JSON looks like this:
[
{
"id": 1,
"title": "Granit",
"typeId": {
"id": 1,
"name": "X or Y",
"acroname": "xory",
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"pushDate": {
"timezone": {
"name": "Europe/Berlin",
"location": {
"country_code": "DE",
"latitude": 52.5,
"longitude": 13.36666,
"comments": "most locations"
}
},
"offset": 7200,
"timestamp": 1460584800
},
"addedAt": {
"timezone": {
"name": "Europe/Berlin",
"location": {
"country_code": "DE",
"latitude": 52.5,
"longitude": 13.36666,
"comments": "most locations"
}
},
"offset": 7200,
"timestamp": 1460548644
},
"deviceToShow": {
"id": 2,
"name": "Mobile",
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"statusSurvey": false,
"slides": [
{
"id": 1,
"title": "First Question",
"picture1": "160413015724bazinga2.jpg",
"picture2": "160413015724th.jpg",
"idSurvey": 1,
"absolutePathpic1": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724bazinga2.jpg",
"webPathpic1": "uploads/slideSurvey/160413015724bazinga2.jpg",
"absolutePathpic2": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724th.jpg",
"webPathpic2": "uploads/slideSurvey/160413015724th.jpg",
"file": null,
"file1": null
}
],
"categories": []
}
]
I want to remove fields like "initializer": null,"cloner": null, "isInitialized": true and hide timezone object and show only "timestamp".
Here is my controller where I'm doing serializing and creating Json Response.
public function getAction()
{
$em = $this->getDoctrine ()->getManager ();
$survey = $em->getRepository ( 'AppBundle:Survey' )->findAll ();
if ( !$survey ) {
throw $this->createNotFoundException ( 'Data not found.' );
}
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler ( function ( $survey ) {
return $survey->getid ();
} );
$serializer = new Serializer( array ( $normalizer ), array ( $encoder ) );
$jsonContent = $serializer->serialize ( $survey, 'json' );
return new Response( $jsonContent );
}
Thank you.

Try to exclude this fields:
$normalilzer->setIgnoredAttributes(
[
"__initializer__",
"__cloner__",
"__isInitialized__"
]);

Detach entity to remove doctrine2 links to the object
$em->detach($survey);

Related

How to count total number of a specific key from a JSON Object in Groovy?

I dont have much experience in using JSONSlurper in Groovy and I have below payload:
{
"header": {
"quoteType": "YQT",
"salesOrg": "2040",
"channel": "02",
"atpMethod": "01",
"distributionChannel": "00",
"division": "00",
"deliveryDateHeader": "2022-10-08T00:00Z",
"isCompleteDeliveryRequired": "",
"shippingCondition": "01",
"pricingDate": "2022-09-02T08:56Z",
"currencyCode": "EUR"
},
"partner": [
{
"partnerNumber": "131761",
"partnerFunction": "SP"
},
{
"partnerNumber": "131762",
"partnerFunction": "WE"
},
{
"partnerNumber": "131761",
"partnerFunction": "RE"
}
],
"materials": [
{
"materialNumber": "29221136",
"requestedDeliveryDate": "2022-10-08T00:00Z",
"deliveryGroup": 0,
"isPartialDeliveryAccepted": "",
"deliveryPlant": null,
"deliveryStorageLocation": null,
"quantity": 1,
"unitOfMeasure": null,
"deliveryPriority": null,
"uomType": "Sales Unit of Measurement"
},
{
"materialNumber": "29233777",
"requestedDeliveryDate": "2022-10-08T00:00Z",
"deliveryGroup": 0,
"isPartialDeliveryAccepted": "",
"deliveryPlant": null,
"deliveryStorageLocation": null,
"quantity": 1,
"unitOfMeasure": null,
"deliveryPriority": null,
"uomType": "Sales Unit of Measurement"
}
]
}
How can I count the total number of "materialNumber"? I have also a code (please check below) but my code does not seem to work as the count is always 0 whenever I run it and I am not also sure on what is wrong.
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper
def Message countMATNR(Message message) {
def reader = message.getBody(InputStream)
def jsonIN = new JsonSlurper().parse(reader)
def property_matnrCounter = 0
jsonIN.materialNumber.each { materials ->
if (materials.materialNumber?.trim() && materials.materialNumber != 'null') {
property_matnrCounter++;
}
}
message.setProperty("numberOfMaterial", property_matnrCounter)
return message;
}
You are addressing the wrong properties, the JSON has a list called materials, and each element in the list is an object which contains the key materialNumber!
If you change it to this, then the result is 2.
jsonIN.materials.each { material ->
if (material.materialNumber?.trim() && material.materialNumber != 'null') {
property_matnrCounter++;
}
}
You can use the out-of-box count() method in a one-liner.
I left irrelevant parts of your json out for brevity.
import groovy.json.JsonSlurper
def json = new JsonSlurper().parseText '''\
{
"materials": [
{
"materialNumber": "29221136",
"requestedDeliveryDate": "2022-10-08T00:00Z",
"deliveryGroup": 0,
"isPartialDeliveryAccepted": "",
"deliveryPlant": null,
"deliveryStorageLocation": null,
"quantity": 1,
"unitOfMeasure": null,
"deliveryPriority": null,
"uomType": "Sales Unit of Measurement"
},
{
"materialNumber": "29233777",
"requestedDeliveryDate": "2022-10-08T00:00Z",
"deliveryGroup": 0,
"isPartialDeliveryAccepted": "",
"deliveryPlant": null,
"deliveryStorageLocation": null,
"quantity": 1,
"unitOfMeasure": null,
"deliveryPriority": null,
"uomType": "Sales Unit of Measurement"
},
{},
{"materialNumber": " "},
{"materialNumber": "null"},
{"materialNumber": null}
]
}'''
int count = json.materials*.materialNumber.count{ it?.trim() && it != 'null' }
assert count == 2

Why does this Laravel eloquent query give back more objects?

I am trying to get back a model that has relationships with other models in Laravel with eloquent but my query does not work. What i am trying to do is only
show the dataLog with the related groups, units and the related component and give that back as a object. The parameter $componentId is the only component that should be given back but it gives back other
component ids, groups and units aswell. Is there a way to only show the component with the given parameter componentId and skip the rest that is not relevant?
<?
public function getLogData( $componentId, $limit ) {
$dataLogs = Log::whereHas( 'groups', function( $group ) use (&$componentId) {
$group->whereHas( "units", function( $unit ) use (&$componentId) {
$unit->whereHas( "components", function( $component ) use (&$componentId) {
$component->where( "Component", $componentId );
} );
} );
} )->take( $limit )->get();
return response( )->json( $dataLogs );
}
?>
The response is
[
{
"Oid": 10409376,
"Active": false,
"Speed": "0",
"Weight": "0",
"Amount": "0",
"Code": "",
"Control": false,
"Type": 1,
"Event": 1,
"Name": "TestName",
"Number": "",
"Mode": 0,
"Recipe": "",
"DateTime": "2020-03-02 11:09:37.177",
"Check": 288,
"groups": [
{
"Oid": 11162074,
"Amount": "3.387",
"Cap": "0",
"Speed": "0",
"ActTachoVoltage": "0",
"Act": "0",
"Weight": "497717",
"Codes": "",
"Type": 1,
"Name": "Group1",
"units": [
{
"Oid": 15934577,
"Speed": "0",
"Counter": 0,
"Weight": "0",
"components": [
{
"oId": 18168546,
"Type": 1,
"component": 1102,
"Entry": 15934577
}
]
},
{
"Oid": 15934578,
"Speed": "0",
"Counter": 0,
"Weight": "0",
"components": [
{
"oId": 18168546,
"Type": 1,
"component": 1101,
"Entry": 15934577
}
]
},
}
]
The response that is needed with the given query
[
{
"Oid": 10409376,
"Active": false,
"Speed": "0",
"Weight": "0",
"Amount": "0",
"Code": "",
"Control": false,
"Type": 1,
"Event": 1,
"Name": "TestName",
"Number": "",
"Mode": 0,
"Recipe": "",
"DateTime": "2020-03-02 11:09:37.177",
"Check": 288,
"groups": [
{
"Oid": 11162074,
"Amount": "3.387",
"Cap": "0",
"Speed": "0",
"ActTachoVoltage": "0",
"Act": "0",
"Weight": "497717",
"Codes": "",
"Type": 1,
"Name": "Group1",
"units": [
{
"Oid": 15934577,
"Speed": "0",
"Counter": 0,
"Weight": "0",
"components": [
{
"Oid": 15934578,
"Speed": "0",
"Counter": 0,
"Weight": "0",
"components": [
{
"oId": 18168546,
"Type": 1,
"component": 1101,
"Entry": 15934577
}
]
},
}
]
If the parameter id given is 1101. Does any one know what i am doing wrong?
The models and the relation ships
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class log extends Model
{
// Define variables
protected $primaryKey = 'Oid';
protected $table = 'log';
protected $connection = 'testdb';
protected $appends = [ 'groups' ];
// Functions
public function getGroupsAttribute( )
{
if( $this->groups() )
return $this->groups()->get();
return [];
}
// Define model relationship logEntry = FK from log to group model
public function groups(){
return $this->hasMany(groupLog::class, 'logEntry');
}
}
?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class groupLog extends Model
{
// Define variables
protected $primaryKey = 'Oid';
protected $table = 'groupLog';
protected $connection = 'testdb';
// Functions
public function getUnitsAttribute( )
{
if( $this->units() )
return $this->units()->get();
return [];
}
// Define database relationships
public function log(){
return $this->belongsTo(log::class);
}
// Define model relationship groupEntry = FK from log to group model
public function units(){
return $this->hasMany(unitLog::class, 'groupEntry');
}
}
?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class unitLog extends Model
{
// Define variables
protected $primaryKey = 'Oid';
protected $table = 'unitLog';
protected $connection = 'testdb';
protected $appends = [ 'components' ];
// Functions
public function getComponentsAttribute( )
{
if( $this->components() )
return $this->components()->get();
return [];
}
// Database relationships with models
public function group(){
return $this->belongsTo(groupLog::class);
}
public function components(){
return $this->hasMany(componentLog::class, 'unitEntry');
}
}
?>
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class componentLog extends Model
{
// Define variables
protected $primaryKey = 'Oid';
protected $table = 'componentLog';
protected $connection = 'testdb';
// Define model database relationships
public function units(){
return $this->belongsTo(unitLog::class);
}
}
?>
Tried the solution with the answer like so
$machineLogs = MachineLog::whereHas( 'groups', function($group) use ($componentId) {
$group->whereHas( "units", function( $unit ) use ($componentId) {
$unit->whereHas( "components", function( $component ) use ($componentId) {
$component->where("component", $componentId);
} );
} );
} );
$filterComponents = $machineLogs->with(['groups.units.components' => function ($query) use ($componentId) {
$query->where('component', $componentId);
}])->take($limit)->get();
return response( )->json( $filterComponents );
You are querying Log that has the given units and it will always return all the units, no matter what ids they have. What you are looking for is to filter the relationship using with(). I would still use your full query, for getting the correct logs out.
Log::yourQueries() // insert your existing queries here.
->with('groups.units.components' => function ($query) use ($componentId) {
$query->where('component', $componentId);
});
This will preload components and filter them by the giving query, this should return your expected result.

Extract individual values from JArray of Lists of JInts

I am practising Scala and Akka Streams on Stripe-payment API. I am looking to extract the transaction date: created from the Json response.
This is the response (showing 2 transactions):
{
"object": "list",
"data": [
{
"id": "txn_1Fqdyl2eZvKYlo2CXfUAnz1z",
"object": "balance_transaction",
"amount": 10000,
"available_on": 1577145600,
"created": 1576581159,
"currency": "usd",
"description": null,
"exchange_rate": null,
"fee": 320,
"fee_details": [
{
"amount": 320,
"application": null,
"currency": "usd",
"description": "Stripe processing fees",
"type": "stripe_fee"
}
],
"net": 9680,
"source": "ch_1Fqdyk2eZvKYlo2CwjSNI1vO",
"status": "available",
"type": "charge"
},
{
"id": "txn_1Fqdyk2eZvKYlo2C7MuBhLpe",
"object": "balance_transaction",
"amount": 2000,
"available_on": 1577145600,
"created": 1576581158,
"currency": "usd",
"description": "テスト支払い",
"exchange_rate": null,
"fee": 88,
"fee_details": [
{
"amount": 88,
"application": null,
"currency": "usd",
"description": "Stripe processing fees",
"type": "stripe_fee"
}
],
"net": 1912,
"source": "ch_1Fqdyk2eZvKYlo2Ccg96i1QQ",
"status": "available",
"type": "charge"
}
],
"has_more": true,
"url": "/v1/balance_transactions"
}
It can vary from 1 to 100 transactions. So far I have been able to extract the value I need when there is only 1 transaction. I need to be able to extract values when there are multiple results. At the moment the value is hardcoded as: case Some(JArray(List(JInt(int)))).
My code:
def epochToDate(epochMillis: BigInt): String = {
val convertedToLong = epochMillis * 1000L
val df:SimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss")
df.format(convertedToLong)
}
val stripe = new Stream("txn_1Fqdyl2eZvKYlo2Cn0OSmwaY", "starting_after", hasMoreFromJson, 1, idFromJson)
stripe.asSource().runForeach(id => {
val rawValue = (parse(id) \ "data" \ "created").toOption
rawValue match {
case Some(JArray(List(JInt(int)))) => println("Date: " + epochToDate(int))
case _ => println("Value not present in JSON")
}
})
Try
val rawValue = (parse(id) \ "data" \\ "created").toOption
rawValue match {
case createdObjOpt: Option[JObject] =>
createdObjOpt match {
case Some(createdObj) =>
createdObj.obj.foreach { created =>
println(created)
}
case None => println("oh no!")
}
case _ => println("Value not present in JSON")
}

Looping and updating data in React

So quite new to React here (mostly backend and devops engineer). I need to fix a bug as the person usually responsible is not available currently.
One of the REST endpoint is formatting dates incorrectly while sending the data to the backend. The data expected from the endpoint for a PUT is
"items": [
{
"uuid": "abc7aba1-47ad-46d1-a3a5-d26ff55e4cf8",
"item_id": "21626227",
"item_description": "Test",
"item_schedule": {
"uuid": "37f8ca4c-6469-4bfb-822e-acfbc02e502e",
"start_date": "2018-12-04",
"end_date": "2018-12-06",
"interval": 3,
"unit": "days",
"occurrence": 1
"schedule_dates": [
{
"uuid": "d5b73ac5-be77-40c5-b11b-45034f70f81f",
"planned_date": "2018-12-04",
"custom": true
}
]
}
},
{
"uuid": "7abca4f4-1717-4136-aec6-3a37b4971c81",
"item_id": "21626229",
"item_description": "Test 2",
"maintenance_plan": "31001827",
"item_schedule": {
"uuid": "5de45d6e-81e8-4c86-9eb2-31c71089c876",
"start_date": null,
"end_date": null,
"interval": null,
"unit": "",
"occurrence": null,
"schedule_dates": [
{
"uuid": "da7ed2e4-053e-4f1d-80ca-2d6d258e8a08",
"planned_date": "2018-12-13",
"custom": true
}
]
}
}
]
Instead what we get for all the dates, i.e. start_date, end_date and planned_dates is (skipping all the right stuff here..)
"end_date": "2018-12-05T13:00:00.000Z",
"start_date": "2018-12-03T13:00:00.000Z"
"planned_date" : "2018-12-03T13:00:00.000Z"
When creating a new schedule for a new item, the old schedule data is incorrectly formatted.
I have tried to loop over all the items and the relevant schedule and dates and correctly format them , but doesn't seem to work.
Do I need to use map here instead of foreach?
const mapDispatchToProps = (dispatch, props) => ({
save: (value, notes) => dispatch(ItemDetailAction.saveLocal(
props.value.merge(
Map(Object.assign(
{
notes: notes.setIn([0, 'created'], undefined),
uuid: props.value.get('uuid'),
},
props.value.getIn(['item', 'type']) === 'P' && {
items: props.value
.get('items').forEach((item) => {
console.log(item.get('item_schedule'));
const start_date = item.get('item_schedule').get('start_date');
if (start_date !== '') {
const formatted_date = moment(start_date).format('YYYY-MM-DD');
//not updating the date-format below in the same array.
item.get('item_schedule').set('start_date',formatted_date);
item.setIn(['item_schedule', 'start_date'],formatted_date);
// this still prints the wrong date-format
console.log(item.get('item_schedule').get('start_date'));
}
}),
},
)),
),
true,
{
then: () => {
props.onCancel();
dispatch(actions.getItemListTable(FilterMaintenance.asParams(props.filters)));
},
}, )), });

Angular http get data and put the json object to a variable

I want to get the nested data in officeid id , code ,name ,shortname, accroym . and put it into individual variable.
How to I do that ???
My code:
{
"id": 1,
"code": "1000-001-1-01-001-001",
"name": "PEACE AND ORDER PROGRAM",
"isActive": true,
"majorFinalOutput": null,
"officeId": 1,
"office": {
"id": 1,
"code": "1-01-001",
"name": "Office of the Governor",
"shortName": "PGO",
"accronym": "PGO",
"website": null,
"email": null,
"telephone": null,
"fax": null,
"type": "1"
},
"sectorId": 1,
"sector": {
"id": 1,
"name": "General Public Services Sector",
"code": "1000",
"parentId": null,
"parent": null
},
"dateCreated": "2018-10-02T14:23:04.913",
"dateModified": null,
"createdBy": null,
"modifiedBy": null
}
getProgram() {
return this.httpClient.get('api/programs/' + idhold).subscribe((holdprogram: any[]) => {
console.log(holdprogram);
});
return this.programService.editProgram().finally( () => {
}).subscribe((holdprogram: any[]) => {
console.log(holdprogram);
console.log(holdprogram.office.id);
console.log(holdprogram.office.name);
console.log(holdprogram.office.shortname);
}, error => {
console.error(error);
},
() => {
});
}
The usual simplest way to keep a reference to a variable obtained via a request is to use a component variable :
in the component :
public export class MyComponent {
...
public office: any; // instead of using 'any', you could create an interface corresponding to the structure
...
}
in the subscribe :
.subscribe((holdprogram: any[]) => {
this.office = holdprogram.office;
console.log(this.office);
// now this.office keeps a reference of your nested variable 'office'.
},
If you need to keep a reference for it across components, it's a bit more comlicated : you could do something similar at the service level (using tap and a local variable), and you'll need to add some more "cache handling" mechanism.