Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: "J.O. Aho" Newsgroups: comp.lang.php Subject: Re: Stripping a JSON of extra characters in PHP Date: Sun, 5 Feb 2023 16:14:32 +0100 Lines: 56 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net ap7VwiW8ih2J/Lin7TnMYQFbiK1rbtoxVVAduizuhw3dMDLnhq Cancel-Lock: sha1:A+RVwjPFA6pWNWLyHfgFfrIz6hU= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.6.1 Content-Language: en-US-large In-Reply-To: Xref: csiph.com comp.lang.php:19297 On 01/02/2023 16:45, The Doctor wrote: > From https://developer.moneris.com/livedemo/checkout/preload_req/guide/dotnet > > I need a JSON as follows: > > { > "store_id":"moneris", > "api_token":"hurgle", For console output: echo json_encode($object, JSON_PRETTY_PRINT); For html output:

If you have an already json encoded string, then you need to use json_decode to get an object and then encode the object to prettify the json. > [{"store_id":"store3","api_token":"yesguy","checkout_id":"chkt23NGFtore3","txn_total":"126.00","environment":"qa","action":"preload"},[{"cart":[[[{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/newwhiteheader.png","description":"Agricultural Health Study","product_code":"AHS-1298","unit_cost":60,"quantity":"1"},"subtotal":60,"tax":{"amount":3,"description":"GST","rate":"0.05"}},{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/newwhiteheader.png","description":"Pesticide Applicator Records","product_code":"PAR-1302","unit_cost":60,"quantity":"1"},"subtotal":60,"tax":{"amount":3,"description":"GST","rate":"0.05"}}]]]}],[{"contact_details":{"first_name":"Dave","last_name":"Yadallee","email":"dog@nk.ca","phone":"7809999999"}}],[{"billing_details":{"address_1":"","city":"","province":"","country":"CA","postal_code":""}}]] > > How can I carefully strip unnecessary punctuation? The unnecessary [] that you get is for you use an array to store things inside, use a class object instead. Here is a small example, where only the cart is an array in the json: --- start of php --- $a = new class{}; $a->store_id = "123"; $a->api_token = "432"; $a->cart = array(); // add item to cart that cast an array to object $a->cart[] = (object)[ "value" => "12.01", "item" => "banana" ]; // add item to cat that is an undefined object $itemObj = new class{}; $itemObj->value = "10.02"; $itemObj->item = "apple"; $a->cart[] = $itemObj; echo json_encode($a, JSON_PRETTY_PRINT); --- eof --- Only use array when you are to have a collection of items, for example a shopping cart, but do not use array when you have a single item, then better to use an object of some sort, for your example I would actually create classes that describes the json, you will of course have nested objects in the end. -- //Aho