Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rewrite raw json in PHP

How can I convert the given code/text into PHP? What would be the PHP syntax of it? There are like some arrays and some objects like items. I would like to restructure it into PHP and be able to convert back to it’s original format if necessary.

{
  "status": "Pending",
  "client": "John",
  "invoice": {
    "series": "INV",
    "currency": "EUR",
    "total": 20,
    "items": [
      {
        "id": 5478,
        "name": "Adapter Lenovo",
        "amount": 1,
        "cost": 10,
      }
    ]
  },
  "parcels": [
    {
      "quantity": "1",
      "weight": 2000
    }
  ],
  "sender": {
    "company": "string",
    "address": {
      "city": "Tallin",
      "street": "New Street"
    }
  },
  "recipient": {
    "name": "Peter",
    "phone": 30258554455
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can convert the string into a an array or object using json_decode()

$json_string = '{
  "status": "Pending",
  "client": "John",
  "invoice": {
    "series": "INV",
    "currency": "EUR",
    "total": 20,
    "items": [
      {
        "id": 5478,
        "name": "Adapter Lenovo",
        "amount": 1,
        "cost": 10
      }
    ]
  },
  "parcels": [
    {
      "quantity": "1",
      "weight": 2000
    }
  ],
  "sender": {
    "company": "string",
    "address": {
      "city": "Tallin",
      "street": "New Street"
    }
  },
  "recipient": {
    "name": "Peter",
    "phone": 30258554455
  }
}';

$arr = json_decode($json_string, true);

var_dump($arr);

And if you want to revert is back to a json string, use json_encode()

$json_string = json_encode( $arr );

json_decode – https://www.php.net/manual/en/function.json-decode.php

json_encode – https://www.php.net/manual/en/function.json-encode.php

*note – the json string you provided in your original question was invalid (there’s a comma after cost).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading