php - 将 JSON 字符串转换为 PHP 代码块
问题描述
有没有一种优雅的方式来转换这个 JSON 字符串:
{
"my_index": 1,
"first_name": "John",
"last_name": "Smith",
"address": {
"address1": "123 Main St",
"address2": "PO Box 123",
"city": "Anywhere",
"state": "CA",
"zip": 12345
}
}
到这个 PHP 代码块:
$data = array();
$data["my_index"] = 1;
$data["first_name"] = "John";
$data["last_name"] = "Smith";
$data["address"] = array();
$data["address"]["address1"] = "123 Main St";
$data["address"]["address2"] = "PO Box 123";
$data["address"]["city"] = "Anywhere";
$data["address"]["state"] = "CA";
$data["address"]["zip"] = 12345;
基本上,构建代码以粘贴到其他内容中。我不想要一个 json_decode()'ed 对象。我真的想以一串 PHP 代码结束,而不是 PHP 对象!
解决方案
不是 100% 与您之后的相同,但它有效地创建了一段您可以使用的 PHP 代码。主要是将其解码为 PHP 数组,然后用于var_export()
输出结果数组。在它周围添加一些样板以提供一些代码......
$data='{
"my_index": 1,
"first_name": "John",
"last_name": "Smith",
"address": {
"address1": "123 Main St",
"address2": "PO Box 123",
"city": "Anywhere",
"state": "CA",
"zip": 12345
}
}';
echo '$data = '.var_export(json_decode($data, true), true).';';
给你
$data = array (
'my_index' => 1,
'first_name' => 'John',
'last_name' => 'Smith',
'address' =>
array (
'address1' => '123 Main St',
'address2' => 'PO Box 123',
'city' => 'Anywhere',
'state' => 'CA',
'zip' => 12345,
),
);
推荐阅读
- wpf - 应用于不同模型的 Listbox DataTemplate
- c# - EF Core:SQLite 删除不是级联的
- php - 已解决:为什么我有“致命错误:未捕获的异常:字符串无法解析为 XML”?
- python - 将 Matlab 单元格转换为 np 数组
- java - 如何检查字符串是否与 Thymeleaf 中的正则表达式匹配?
- windows - 坚持在 Windows 上使用 Kafka 代理
- python - 如何在 python flask sqlalchemy 和 postgresql 中设计一个引用代码系统
- django - 在视图流中将任务号分配给当前用户
- geojson - 在六角网格中查找点的有效方法
- vb.net - OracleDataReader Reader.Read() 显示枚举未产生任何结果,但行数为真