首页 > 解决方案 > Symfony 4 命令行发送 JSON 字符串数组

问题描述

嗨,我学习 PHP 和 Symfony。我试着做那个节目:

命令必须采用包含 JSON 格式产品数组的字符串参数。它应该返回 JSON 字符串数组,其中产品按价格升序排序,如果价格相同,则按字母升序排序。示例 JSON 参数:

```
[   
{
    "title": "H&M T-Shirt White",
    "price": 10.99,
    "inventory": 10
},
{
    "title": "Magento Enterprise License",
    "price": 1999.99,
    "inventory": 9999
},
{
    "title": "iPad 4 Mini",
    "price": 500.01,
    "inventory": 2
},
{
    "title": "iPad Pro",
    "price": 990.20,
    "inventory": 2
},
{
    "title": "Garmin Fenix 5",
    "price": 789.67,
    "inventory": 34
},
{
    "title": "Garmin Fenix 3 HR Sapphire Performer Bundle",
    "price": 789.67,
    "inventory": 12
}
]
```

问题是我无法进入控制台。我还没有找到将 JSON 对象输入控制台的方法。我尝试手动执行此操作,但问题是我稍后会收到严重切碎的文本。这是由于 ("") 和 ('')。例如:

 php .\bin\console js_arr "{'title': 'H&M T-Shirt White', 'price': 
 10.99,'inventory': 10},{'title': 'Magent
 o Enterprise License','price':1999.99,'inventory': 9999}"
 array(1) {
 [0]=>
  string(136) "{'title': 'H&M T-Shirt White', 'price': 10.99,'inventory': 
 10},{'title': 'Magento Enterprise License','price':1999.99,'inventory': 
 9999}"
 }

我有很好的字符串发送到程序,但我需要手动更改引号。

PS D:\comand> php .\bin\console js_arr '{"title": "H&M T-Shirt White", 
"price": 10.99,"inventory": 10},{"title": "Magent
o Enterprise License","price":1999.99,"inventory": 9999}'
array(5) {
[0]=>
string(11) "{title: H&M"
[1]=>
string(7) "T-Shirt"
[2]=>
string(50) "White, price: 10.99,inventory: 10},{title: Magento"
[3]=>
string(10) "Enterprise"
[4]=>
string(38) "License,price:1999.99,inventory: 9999}"
}

这是一个不好的例子

请提出建议和提示。

标签: phpjsoncommand-linesymfony4

解决方案


任何一个

您使用转义的双引号传递您的 JSON

php bin/console my:myCommand {\"foo\":\"bar\"}

在您的命令类中,您将收到它作为有效的 JSON {"foo":"bar"}

然后解析它 $argument = json_decode($input->getArgument('myArgumentKey'), true);

或者

就像建议的 ILikeTacos 一样,不要将 json 传递给命令,将其放入文件中,也许在 yml 中,然后让您的命令读取此文件并解析数据。

为了允许更复杂的 JSON 结构和更高的可用性,我更喜欢这个解决方案,所以你不必每次都添加反斜杠。


推荐阅读