从一种json格式转换为另一种格式

时间:2015-05-07 08:56:21

标签: php json string

我有一个JSON格式的字符串,我从API调用中得到。但是我从API调用获得的JSON字符串的格式与此类似。

let image = UIImage(named: "Image")

我希望它采用以下格式

{"offset":1,"result":{"host":"x.x.x.x","count":123"}}

注意:请注意折叠JSON中的附加方括号。

我如何在PHP中实现这一目标。我是一个相当新的PHP一点点帮助在这里表示赞赏。谢谢:))

4 个答案:

答案 0 :(得分:0)

将原始转换为JSON对象,取出result

var originalJSONObj = JSON.parse(original);
var result = originalJSONObj.result;

使用modifiedJSONObj.offset = 1modifiedJSONObj.result = []以及最后modifiedJSONObj.result.push(result)创建另一个对象。

答案 1 :(得分:0)

在PHP中,类似于:

$json = '{"offset":1,"result":{"host":"x.x.x.x","count":123}}';
$data = json_decode($json);
$data->result = [$data->result];
$json = json_encode($data);
var_dump($json);

答案 2 :(得分:0)

您应该可以使用PHP的json_decode()json_encode()函数执行此操作。类似的东西:

$jsonFromApi = '{"offset":1,"result":{"host":"x.x.x.x","count":123}}';
$array = json_decode($jsonFromApi, true);
$array['result'] = array($array['result']);
$newJson = json_encode($array);

编辑:以下是使用foreach对一系列逗号分隔的json字符串执行此操作的示例。

$originalData = '{"offset":1,"result":{"host":"x.x.x.x","count":123}},{"offset":2,"result":{"host":"x.x.x.x","count":123}},{"offset":3,"result":{"host":"x.x.x.x","count":123}}';

// Convert original data to valid JSON by wrapping it in brackets []. Makes it a JSON array.
$json = '['.$originalData.']';
$array = json_decode($json, true);

$convertedJsonStrings = array();
foreach ($array as $data) {
    $data['result'] = array($data['result']);
    $convertedJsonStrings[] = json_encode($data);
}
echo implode(',', $convertedJsonStrings);

我们无法直接将json_decode()用于$originalData,因为它不是JSON原样。

答案 3 :(得分:0)

// i fixed the json that you are able to receive from the api
// maybe you could check it also
$data = '{
    "offset": 1,
    "result": {
        "host": "x.x.x.x",
        "count": "123"
    }
}';

// decode the json from api
$data = json_decode($data, true);

// create new data from decoded data
$new_data = array(
    'ofsset' => $data['offset'],
    'result' => array(
        $data['result']
    )
);

// encode it again 
echo json_encode($new_data);
相关问题