[英]Format JSON Output
I am passing a WordPress custom post type as a JSON feed to my app.我正在将 WordPress 自定义帖子类型作为 JSON 提要传递给我的应用程序。
I created a JSON page template which queries and displays the results as below:我创建了一个 JSON 页面模板,它查询并显示如下结果:
$directories [] = array(
'subtype' => 'mcms',
'type' => 'maps',
'summary' => get_the_title(),
'title' => get_the_title(),
'address' => get_field('address'),
'content' => get_the_content(),
'author' => get_the_author()
);
endwhile;
wp_reset_query();
echo json_encode ($directories);
The output from this is:输出结果是:
[
{
"subtype": "mcms",
"type": "maps",
"summary": "Directory Listing",
"title": "Directory Listing",
"address": false,
"content": "Lorem ipsum dolor sit amet",
"author": "admin"
}
]
I would like to format the output as follows:我想按如下方式格式化输出:
"items:" [
{
"subtype": "mcms",
"type": "maps",
"summary": "Directory Listing",
"title": "Directory Listing",
"address": false,
"content": "Lorem ipsum dolor sit amet",
"author": "admin"
}
]
I am trying the following:我正在尝试以下操作:
echo "items: ", json_encode ($directories);
But the output isn't JSON formatted which I need但输出不是我需要的 JSON 格式
Any help?有什么帮助吗?
Wrap your $directories
in an array before you call json_encode
.在调用json_encode
之前将您的$directories
包装在一个数组中。
$items = ['items' => $directories];
echo json_encode($items);
Adding the directories in an array is the solution:在数组中添加目录是解决方案:
echo json_encode (array('items' => $directories)); echo json_encode (array('items' => $directories));
Change this line改变这一行
$directories[] = array(...
To this对此
$directories['items'][] = array(...
And your echo leave it as this而你的回声就这样离开了
echo json_encode($directories);
you could get your output to be like this:你可以让你的输出是这样的:
[
{
"items:" [
{
"subtype": "mcms",
"type": "maps",
"summary": "Directory Listing",
"title": "Directory Listing",
"address": false,
"content": "Lorem ipsum dolor sit amet",
"author": "admin"
}
]
}
]
you need to create an Object for the items, and then create a hashmap您需要为项目创建一个对象,然后创建一个哈希图
Map<String, List<KeyValue>> map = new HashMap();
map.put("items", itemObject);
JsonBuilderFactory jsnFactory = Json.createBuilderFactory(null);
JsonObjectBuilder builder = jsnFactory.createObjectBuilder();
for (String key : map.keySet()) {
builder.add(keu,map.get(key));
}
return builder.build().toString();
return返回
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.