以正确的方式创建JSON对象 [英] Create JSON-object the correct way

查看:126
本文介绍了以正确的方式创建JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从PHP数组创建JSON对象.数组如下所示:

I am trying to create an JSON object out of a PHP array. The array looks like this:

$post_data = array('item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
    'is_public_for_contacts' => $public_contacts);

用于编码JSON的代码如下:

The code to encode the JSON look like this:

$post_data = json_encode($post_data);

JSON文件最后应该看起来像这样:

The JSON file is supposed to look like this in the end:

{
    "item": {
        "is_public_for_contacts": false,
        "string_extra": "100000583627394",
        "string_value": "value",
        "string_key": "key",
        "is_public": true,
        "item_type_id": 4,
        "numeric_extra": 0
    }
} 

如何将创建的JSON代码封装在项目"中:{JSON CODE HERE}.

How can I encapsulate the created JSON code in the "item": { JSON CODE HERE }.

推荐答案

通常,您会执行以下操作:

Usually, you would do something like this:

$post_data = json_encode(array('item' => $post_data));

但是,似乎您希望输出使用"{}",所以最好确保强制

But, as it seems you want the output to be with "{}", you better make sure to force json_encode() to encode as object, by passing the JSON_FORCE_OBJECT constant.

$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);

"{}"括号指定一个对象,"[]"用于根据JSON规范的数组.

"{}" brackets specify an object and "[]" are used for arrays according to JSON specification.

这篇关于以正确的方式创建JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆