在PHP中重写原始json [重复]

zwghvu4y  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(93)

这个问题已经有答案了

How to extract and access data from JSON with PHP?(1个答案)
关闭7天前。
如何将给定的代码/文本转换为PHP?它的PHP语法是什么?这里有一些数组和一些像项目一样的对象。我想把它重组成PHP,并能够转换回它的原始格式,如果必要的。

{
  "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
  }
}
ibps3vxo

ibps3vxo1#

可以使用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);

如果你想恢复为json字符串,使用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

  • 注意-您在原始问题中提供的json字符串无效(cost后面有一个逗号)。

相关问题