Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.php > #19258 > unrolled thread

Stripping [ ] from JSON arrays

Started bydoctor@doctor.nl2k.ab.ca (The Doctor)
First post2023-01-10 01:17 +0000
Last post2023-02-16 04:51 -0800
Articles 7 — 5 participants

Back to article view | Back to comp.lang.php


Contents

  Stripping [ ] from JSON arrays doctor@doctor.nl2k.ab.ca (The Doctor) - 2023-01-10 01:17 +0000
    Re: Stripping [ ] from JSON arrays JJ <jj4public@outlook.com> - 2023-01-10 11:29 +0700
      Re: Stripping [ ] from JSON arrays Elhwen Dico <elhwen.dicote@gmail.com> - 2023-01-11 17:09 +0100
        Re: Stripping [ ] from JSON arrays doctor@doctor.nl2k.ab.ca (The Doctor) - 2023-01-11 16:18 +0000
      Re: Stripping [ ] from JSON arrays Y A <y000000000000@ya.ee> - 2023-02-16 04:50 -0800
    Re: Stripping [ ] from JSON arrays Stefan+Usenet@Froehlich.Priv.at (Stefan Froehlich) - 2023-01-10 08:10 +0000
      Re: Stripping [ ] from JSON arrays Y A <y000000000000@ya.ee> - 2023-02-16 04:51 -0800

#19258 — Stripping [ ] from JSON arrays

Fromdoctor@doctor.nl2k.ab.ca (The Doctor)
Date2023-01-10 01:17 +0000
SubjectStripping [ ] from JSON arrays
Message-ID<tpiebr$cso$64@gallifrey.nk.ca>
This morning I got this from Moeris:


Here's an example working one:

{
"store_id":"store3",
"checkout_id":"chkt23NGFtore3",
"api_token":"yesguy",
"txn_total":"189.00",
"environment":"qa",
"action":"preload"
}

You repeated the same items section 3 times and your commas and braces are
incorrectly placed. Correct your preload, and let me know if you still get a
blank screen.

Follow the formatting shown here for the preload:
https://developer.moneris.com/sitecore/media%20library/Hidden/MCO/Preload%20Request?sc_lang=en


now given code processor



<?=session_start();
error_reporting(E_ALL);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Professional Development Solutions - Online Form</title>
<meta name="description" content="PD Solutions is an educational company that delivers on-line webinars and webcasts to various organizations or people" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" type="text/css" href="css/css.css"/>
<link rel="stylesheet" type="text/css" href="css/css2.css"/>
    <link rel="stylesheet" href="css/uniform.default.css" type="text/css" media="screen">
    <link rel="stylesheet" href="css/uniform.agent.css" type="text/css" media="screen">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">


</head>
<body>
<?php 
 if(!empty($_SESSION['sessiondata'])){
 }
?>
<div id="wrapper">
 <!--header begins-->
 <?php
  include("includes/header.php");
 ?> 
<!--header ends-->
<FORM ACTION="https://gatewayt.moneris.com/chktv2/request/request.php" method=post>
<?php 
$myObj = [];
$cartarray= [];
$itemssubarray= [];
$storevalues= [];
$storevalues2= [];
$contact_details=[];
$shipping_details=[];
$billing_details=[];
$arr2 =array();
?>
<center>
<!-- Store Settings-->
<!------- DEFINE CHARGE TOTAL HERE --->
<br/><br/><h3>Your Purchase Total Is: </h3> <br/> <h2>$<?=$_POST['charge_total']?></h2> 
<!-- Unique Order ID -->
<!-- Additional Optional Details -->
<!-- Item Information -->
<?php 

$items_count = 1;
$subtotal = 0;
$subtotala = 0;
$arr = array();
if (isset($_POST["submit"])){
foreach ($_POST['quantity'] as $key => $value) {

  if( $value > 0){

    if(isset($_POST['with_gst'][$key])){
      $unit_cost = 63.00;
    }else{
      $unit_cost = 60.00; //no gst included
    }

    $subtotal = ($unit_cost * $value);
    $quantity = ($value);
    
    $itemssubarray[] = array(
		"items"=>array(
         'url' => "https://www.pdsolutions.ca/images/procircle.png",
	'description' => $_POST['description'][$key],
	'product_code' => $_POST['id'][$key],
       'unit_cost' => $unit_cost,
	'quantity' => $quantity,
		),
    );
}
 
  $subtotala += ($unit_cost * $value);
  $items_count++;
}
  $cartarray[] = array ("cart"=>array($itemssubarray));

//  array_push($cartarray,$itemssubasrray);
 
    $cartarray[] = array(
	'subtotal' => $subtotala,
	"tax"=>array(
          'amount' => ($subtotala * 0.05),
          'description' => "GST",
	  'rate' => "0.05",
          ),
    );
    array_push($arr, $cartarray);
}    

?>
<?php 

if (isset($_POST["submit"])){
(array_push($storevalues,[
//'sessValue' => $_POST['sessionid1'],
'username'=> "demouser",
'password' => "password",
'store_id' => "store3",
'checkout_id' => "chkt23NGFtore3",
'api_token' => "yesguy",
'txn_total' => $_POST['charge_total'],
'environment' => "qa",
'action' => "preload",
]));

    $contact_details[] = array(
	    "contact_details"=>array(
'first_name' =>$_POST['bill_first_name'],
'last_name' => $_POST['bill_last_name'],
'email' => $_POST['email'],
'phone' => $_POST['bill_phone'],
	    )
);
    array_push($arr2, $contact_details);

	$billing_details[] = array (
		"billing_details"=>array(
'address_1' => $_POST['bill_address_one'],
'city' => $_POST['bill_city'],
'province' => $_POST['bill_state_or_province'],
'country' => "CA",
'postal_code' => $_POST['bill_postal_code'],

		)
	);	

?>
<?php 
$myObj = array_merge($storevalues,$cartarray,$contact_details,$billing_details);
//$storevalues2 = substr($storevalues,1,strlen($storevalues) -2);
//$myObj = $storevalues;
$myJSON =  json_encode($myObj);
echo $myJSON;
}

?>
<div id="outerDiv" style="width:400px"; height"300px">`
<div id="monerisCheckout">
</div>

</div>
<script src="https://gatewayt.moneris.com/chktv2/js/chkt_v2.00.js" async></script>

 <script>
        var myCheckout = new monerisCheckout();
        myCheckout.setMode("qa");
        myCheckout.setCheckoutDiv("monerisCheckout");
        monerisCheckout.startCheckout('<?php echo $token ?>');
 
        var myPageLoad = function(data) {
            console.log(data);
            const obj = JSON.parse(data);
            console.log(obj.ticket);
 
        };
 
        var myCancelTransaction = function(data) {
            console.log(data);
            const obj = JSON.parse(data);
            console.log(obj.ticket);
        };
 
        var myErrorEvent = function(data) {
            console.log(data);
            const obj = JSON.parse(data);
            console.log(obj.ticket);
        };
 
        var myPaymentReceipt = function(data) {
            console.log(data);
            const obj = JSON.parse(data);
            console.log(obj.ticket);
        };
 
        var myPaymentComplete = function(data) {
            console.log(data);
            const obj = JSON.parse(data);
            console.log(obj.ticket);
        };
 
        /**
        * Set callbacks in JavaScript:
        */
        myCheckout.setCallback("page_loaded",myPageLoad);
        myCheckout.setCallback("cancel_transaction",myCancelTransaction);
        myCheckout.setCallback("error_event", myErrorEvent);
        myCheckout.setCallback("payment_receipt",myPaymentReceipt);
        myCheckout.setCallback("payment_complete", myPaymentComplete);
    </script>
<INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="Click to proceed to Secure Page">
</center>
</FORM>

<?php 
    include("includes/footer.php");
?>
</div>
</body>
</html>


This picks up data from a previous form.

Here is and example of what is generated:

[{"username":"demouser","password":"password","store_id":"store3","checkout_id":"chkt23NGFtore3","api_token":"yesguy","txn_total":"189.00","environment":"qa","action":"preload"},{"cart":[[{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Protecting Pollinators","product_code":"PP-1294","unit_cost":60,"quantity":"1"}},{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Agricultural Health Study","product_code":"AHS-1298","unit_cost":60,"quantity":"1"}},{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Pesticide Applicator Records","product_code":"PAR-1302","unit_cost":60,"quantity":"1"}}]]},{"subtotal":180,"tax":{"amount":9,"description":"GST","rate":"0.05"}},{"contact_details":{"first_name":"Dave","last_name":"Yadallee","email":"root@nk.ca","phone":"7804734587"}},{"billing_details":{"address_1":"","city":"","province":"","country":"CA","postal_code":""}}]

And here is what is being looked for

{
    "store_id":"moneris",
	"api_token":"hurgle",
	    "checkout_id":"chkt5BF66neris",
		"txn_total":"452.00",
		    "environment":"qa",
			"action":"preload",
			    "token": [
				{
					"data_key": "abc123datakey1",
						"issuer_id": "645sddfvdrt4tefd"
						    },
							{
								"data_key": "abc123datakey2",
									"issuer_id": "645sddfvdrt4tefd"
									    },
										{
											"data_key": "abc123datakey3",
												"issuer_id": "645sddfvdrt4tefd"
												    }
													],
													    "ask_cvv":"Y"
														"order_no":"",
														    "cust_id":"chkt - cust - 0303",
															"dynamic_descriptor":"dyndesc",
															    "language":"en",
																"recur":{
																	"bill_now":"true",
																		"recur_amount":"1.00",
																			"start_date":"2021-11-21",
																				"recur_unit":"month",
																					"recur_period":"1",
																						"number_of_recurs":"10"
																						    },
																							"cart":{
																								"items":[
																									    {
																											    "url":"https:\/\/example.com\/examples\/item1.jpg",
																													    "description":"One item",
																															    "product_code":"one_item",
																																	    "unit_cost":"100.00",
																																			    "quantity":"1"
																																					},
																																						    {
																																								    "url":"https:\/\/example.com\/examples\/item2.jpg",
																																										    "description":"Two item",
																																												    "product_code":"two_item",
																																														    "unit_cost":"200.00",
																																																    "quantity":"1"
																																																		},
																																																			    {
																																																					    "url":"https:\/\/example.com\/examples\/item3.jpg",
																																																							    "description":"Three item",
																																																									    "product_code":"three_item",
																																																											    "unit_cost":"100.00",
																																																													    "quantity":"1"
																																																															}
																																																																],
																																																																	"subtotal":"400.00",
																																																																		    "tax":{
																																																																				"amount":"52.00",
																																																																					    "description":"Taxes",
																																																																							"rate":"13.00"
																																																																								}
																																																																								    },
																																																																									"contact_details":{
																																																																										"first_name":"bill",
																																																																											"last_name":"smith",
																																																																												"email":"test@moneris.com",
																																																																													"phone":"4165551234"
																																																																													    },
																																																																														"shipping_details":{
																																																																															"address_1":"1 main st",
																																																																																"address_2":"Unit 2012",
																																																																																	"city":"Toronto",
																																																																																		"province":"ON",
																																																																																			"country":"CA",
																																																																																				"postal_code":"M1M1M1"
																																																																																				    },
																																																																																					"billing_details":{
																																																																																						"address_1":"1 main st",
																																																																																							"address_2":"Unit 2000",
																																																																																								"city":"Toronto",
																																																																																									"province":"ON",
																																																																																										"country":"CA",
																																																																																											"postal_code":"M1M1M1"
																																																																																											    }
																																																																																											    }

																																																																																											    How do I strip unnecessary [] ?
-- 
Member - Liberal International This is doctor@nk.ca Ici doctor@nk.ca
Yahweh, King & country!Never Satan President Republic!Beware AntiChrist rising!
Look at Psalms 14 and 53 on Atheism https://www.empire.kred/ROOTNK?t=94a1f39b 
Birthdate: 29 Jan 1969 Redhill, Surrey, England  Beware https://mindspring.com

[toc] | [next] | [standalone]


#19259

FromJJ <jj4public@outlook.com>
Date2023-01-10 11:29 +0700
Message-ID<1rb3ua6kn88tn.objz7l6azwbd.dlg@40tude.net>
In reply to#19258
On Tue, 10 Jan 2023 01:17:47 -0000 (UTC), The Doctor wrote:
> 
> How do I strip unnecessary [] ?

I'd use array's `reduce()` for that. e.g.

var resultObj = theArray.reduce((res, obj) => Object.assign(res, obj), {});

[toc] | [prev] | [next] | [standalone]


#19261

FromElhwen Dico <elhwen.dicote@gmail.com>
Date2023-01-11 17:09 +0100
Message-ID<63bedf36$0$3100$426a34cc@news.free.fr>
In reply to#19259
Le 10/01/2023 à 05:29, JJ a écrit :
> On Tue, 10 Jan 2023 01:17:47 -0000 (UTC), The Doctor wrote:
>>
>> How do I strip unnecessary [] ?
> 
> I'd use array's `reduce()` for that. e.g.
> 
> var resultObj = theArray.reduce((res, obj) => Object.assign(res, obj), {});

     const array = [
         [0, 1, 2], [], ["tutu"], undefined
     ];

     const result = array.filter(
         (tab) => (tab && tab.length));

     console.log(result);

-> [ [ 0, 1, 2 ], [ 'tutu' ] ]

   you could improve filter callback to check that array members are arrays.

[toc] | [prev] | [next] | [standalone]


#19262

Fromdoctor@doctor.nl2k.ab.ca (The Doctor)
Date2023-01-11 16:18 +0000
Message-ID<tpmngk$12k$94@gallifrey.nk.ca>
In reply to#19261
In article <63bedf36$0$3100$426a34cc@news.free.fr>,
Elhwen Dico  <elhwen.dicote@gmail.com> wrote:
>Le 10/01/2023 à 05:29, JJ a écrit :
>> On Tue, 10 Jan 2023 01:17:47 -0000 (UTC), The Doctor wrote:
>>>
>>> How do I strip unnecessary [] ?
>> 
>> I'd use array's `reduce()` for that. e.g.
>> 
>> var resultObj = theArray.reduce((res, obj) => Object.assign(res, obj), {});
>
>     const array = [
>         [0, 1, 2], [], ["tutu"], undefined
>     ];
>
>     const result = array.filter(
>         (tab) => (tab && tab.length));
>
>     console.log(result);
>
>-> [ [ 0, 1, 2 ], [ 'tutu' ] ]
>
>   you could improve filter callback to check that array members are arrays.

giving an update, I finally found someone at Moneris to work with.

I hate bad doumentation.
-- 
Member - Liberal International This is doctor@nk.ca Ici doctor@nk.ca
Yahweh, King & country!Never Satan President Republic!Beware AntiChrist rising!
Look at Psalms 14 and 53 on Atheism https://www.empire.kred/ROOTNK?t=94a1f39b 
Birthdate: 29 Jan 1969 Redhill, Surrey, England  Beware https://mindspring.com

[toc] | [prev] | [next] | [standalone]


#19334

FromY A <y000000000000@ya.ee>
Date2023-02-16 04:50 -0800
Message-ID<79d2b4cc-e6c0-436e-ac98-e8cdfaeaf004n@googlegroups.com>
In reply to#19259
You have looked out: http://webchatsoftware.ezyro.com ?




On Tuesday, January 10, 2023 at 6:29:21 AM UTC+2, JJ wrote:
> On Tue, 10 Jan 2023 01:17:47 -0000 (UTC), The Doctor wrote: 
> > 
> > How do I strip unnecessary [] ?
> I'd use array's `reduce()` for that. e.g. 
> 
> var resultObj = theArray.reduce((res, obj) => Object.assign(res, obj), {});

[toc] | [prev] | [next] | [standalone]


#19260

FromStefan+Usenet@Froehlich.Priv.at (Stefan Froehlich)
Date2023-01-10 08:10 +0000
Message-ID<1t63bd197bi3c78e5n3e8%sfroehli@Froehlich.Priv.at>
In reply to#19258
In comp.lang.php The Doctor <doctor@doctor.nl2k.ab.ca> wrote:
> $contact_details=[];
[...]
>     $contact_details[] = array(
>             "contact_details"=>array(
> 'first_name' =>$_POST['bill_first_name'],
> 'last_name' => $_POST['bill_last_name'],
> 'email' => $_POST['email'],
> 'phone' => $_POST['bill_phone'],
>             )
> );
[...]
> $myObj = array_merge($storevalues,$cartarray,$contact_details,$billing_details);
> $myJSON =  json_encode($myObj);

> Here is and example of what is generated:
 
> [{"username":"demouser","password":"password","store_id":"store3","checkout_id":"chkt23NGFtore3","api_token":"yesguy","txn_total":"189.00","environment":"qa","action":"preload"},{"cart":[[{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Protecting Pollinators","product_code":"PP-1294","unit_cost":60,"quantity":"1"}},{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Agricultural Health Study","product_code":"AHS-1298","unit_cost":60,"quantity":"1"}},{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Pesticide Applicator Records","product_code":"PAR-1302","unit_cost":60,"quantity":"1"}}]]},{"subtotal":180,"tax":{"amount":9,"description":"GST","rate":"0.05"}},{"contact_details":{"first_name":"Dave","last_name":"Yadallee","email":"root@nk.ca","phone":"7804734587"}},{"billing_details":{"address_1":"","city":"","province":"","country":"CA","postal_code":""}}]
 
> And here is what is being looked for
> 
> {
>     "store_id":"moneris",
>     [...]
> }

>  How do I strip unnecessary [] ?

First of all, you should strip unnecessary information from your
postings - in your case the content of $myObj and the output are the
only necessary information.

#v+
$a = array();
$b = array();
$a[] = ['contact_details' => ['y' => 'z']];
$b[] = ['billing_details' => ['y' => 'z']];
$c = array_merge($a, $b);
var_dump(json_encode($c));
#v-

string(59) "[{"contact_details":{"y":"z"}},{"billing_details":{"y":"z"}}]"


#v+
$a = ['contact_details' => ['y' => 'z']];
$b = ['billing_details' => ['y' => 'z']];
$c = array_merge($a, $b);
var_dump(json_encode($c));
#v-

string(55) "{"contact_details":{"y":"z"},"billing_details":{"y":"z"}}"

So there is no need to use reduce() or anything else. You are simply
using one (non-associative) level of arrays too much. This would be
easier to debug if you add a print_r($myObj); to your debugging
output.


Personally I'd prefer another version without the irritating
array_merge for better readability, but this is just a matter of
taste producing the same array and the same output:

#v+
$a = ['y' => 'z'];
$b = ['y' => 'z'];
$c = ['contact_details' => $a, 'billing_details' => $b];
var_dump(json_encode($c));
#v-

Bye,
  Stefan

-- 
http://kontaktinser.at/ - die kostenlose Kontaktboerse fuer Oesterreich
Offizieller Erstbesucher(TM) von mmeike

Stefan: die süße Verführung!
(Sloganizer)

[toc] | [prev] | [next] | [standalone]


#19335

FromY A <y000000000000@ya.ee>
Date2023-02-16 04:51 -0800
Message-ID<e89b285b-28c6-47d4-8c6d-74832b197e29n@googlegroups.com>
In reply to#19260
You have looked out: http://webchatsoftware.ezyro.com ?




On Tuesday, January 10, 2023 at 10:10:19 AM UTC+2, Stefan Froehlich wrote:
> In comp.lang.php The Doctor <doc...@doctor.nl2k.ab.ca> wrote: 
> > $contact_details=[]; 
> [...]
> > $contact_details[] = array( 
> > "contact_details"=>array( 
> > 'first_name' =>$_POST['bill_first_name'], 
> > 'last_name' => $_POST['bill_last_name'], 
> > 'email' => $_POST['email'], 
> > 'phone' => $_POST['bill_phone'], 
> > ) 
> > );
> [...] 
> > $myObj = array_merge($storevalues,$cartarray,$contact_details,$billing_details); 
> > $myJSON = json_encode($myObj);
> > Here is and example of what is generated: 
> 
> > [{"username":"demouser","password":"password","store_id":"store3","checkout_id":"chkt23NGFtore3","api_token":"yesguy","txn_total":"189.00","environment":"qa","action":"preload"},{"cart":[[{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Protecting Pollinators","product_code":"PP-1294","unit_cost":60,"quantity":"1"}},{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Agricultural Health Study","product_code":"AHS-1298","unit_cost":60,"quantity":"1"}},{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Pesticide Applicator Records","product_code":"PAR-1302","unit_cost":60,"quantity":"1"}}]]},{"subtotal":180,"tax":{"amount":9,"description":"GST","rate":"0.05"}},{"contact_details":{"first_name":"Dave","last_name":"Yadallee","email":"ro...@nk.ca","phone":"7804734587"}},{"billing_details":{"address_1":"","city":"","province":"","country":"CA","postal_code":""}}] 
> 
> > And here is what is being looked for 
> > 
> > { 
> > "store_id":"moneris",
> > [...]
> > } 
> 
> > How do I strip unnecessary [] ?
> First of all, you should strip unnecessary information from your 
> postings - in your case the content of $myObj and the output are the 
> only necessary information. 
> 
> #v+ 
> $a = array(); 
> $b = array(); 
> $a[] = ['contact_details' => ['y' => 'z']]; 
> $b[] = ['billing_details' => ['y' => 'z']]; 
> $c = array_merge($a, $b); 
> var_dump(json_encode($c)); 
> #v- 
> 
> string(59) "[{"contact_details":{"y":"z"}},{"billing_details":{"y":"z"}}]" 
> 
> 
> #v+ 
> $a = ['contact_details' => ['y' => 'z']]; 
> $b = ['billing_details' => ['y' => 'z']]; 
> $c = array_merge($a, $b); 
> var_dump(json_encode($c)); 
> #v- 
> 
> string(55) "{"contact_details":{"y":"z"},"billing_details":{"y":"z"}}" 
> 
> So there is no need to use reduce() or anything else. You are simply 
> using one (non-associative) level of arrays too much. This would be 
> easier to debug if you add a print_r($myObj); to your debugging 
> output. 
> 
> 
> Personally I'd prefer another version without the irritating 
> array_merge for better readability, but this is just a matter of 
> taste producing the same array and the same output: 
> 
> #v+ 
> $a = ['y' => 'z']; 
> $b = ['y' => 'z']; 
> $c = ['contact_details' => $a, 'billing_details' => $b]; 
> var_dump(json_encode($c)); 
> #v- 
> 
> Bye, 
> Stefan 
> 
> -- 
> http://kontaktinser.at/ - die kostenlose Kontaktboerse fuer Oesterreich 
> Offizieller Erstbesucher(TM) von mmeike 
> 
> Stefan: die süße Verführung! 
> (Sloganizer)

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.php


csiph-web