Perl REST客户端模块 - 如何在更新后放回整个JSON

时间:2014-10-13 00:04:06

标签: perl rest

我正在使用第三方REST API来更新用户对象。用户对象的格式类似于:

{
        "id": "abcd1234",
        "profile": {
            "firstName": "Test",
            "lastName": "User",
            "email": "test@somedomain.com",
            ....
        }
}

我正在进行GET调用以获取用户对象,其中$ next是我的GET命令。我想更新email属性并将整个JSON对象放回去。然后,我执行以下代码取消引用对象并获取电子邮件属性(如下所示)。特定API要求在更新用户的配置文件时指定所有配置文件属性。供应商的api不支持部分更新。如何将电子邮件属性值更新为其他内容,并将整个json对象放回原处?我正在寻找剩余的代码来帮助实现这一目标。

use JSON qw( decode_json );
use REST::Client;
....

$next = "/api/v1/users?q=Test_User";
$cli->GET($next); 
$json = $cli->responseContent();
my $perl_ref = decode_json($json); #decode the response
foreach my $item( @$perl_ref ) 
{ 
        $email = $item->{'profile'}->{'email'}; #deference email value from user object
        #Update the email attribute value for referenced user object
        #re-encode as JSON, and PUT the entire record to update it

}

从GET调用返回的JSON看起来像这样(如下)。当我执行PUT时,我想更新电子邮件属性值,但我只想删回配置文件部分而不是其他任何内容。我如何更改代码才能实现此目的?

{
    "id": "00u1ujjbx5AZCKALPVHM",
    "passwordChanged": null,
    "profile": {
        "firstName": "John",
        "email": "test@somedomain.com",
    },
    "credentials": {
        "rec_question": {
            "question": "What is your favorite food?"
        },
        "provider": {
            "type": "ACTIVE_DIRECTORY",
            "name": "domain.local"
        }
    },
    "_links": {
        "changeRecoveryQuestion": {
            "href": "abc",
            "method": "POST"
        },
        "deactivate": {
            "href": "def",
            "method": "POST"
        },
        "changePassword": {
            "href": "ghi",
            "method": "POST"
        }
    }
}

1 个答案:

答案 0 :(得分:1)

只需更新参考对象,然后重新编码回json。

#Update the email attribute value for referenced user object
my $my_new_email = "someone@example.com";
$item->{'profile'}->{'email'} = $my_new_email;

#re-encode as JSON, 
my $json_out = encode_json( $item );

#and PUT the entire record to update it
$cli->PUT( $json_out );

但是,您应该检查API是否支持PATCH - 这允许您发送回您想要更新的字段,而不必进行初始获取,您可以将上面的示例缩减为:

$cli->PATCH(  '{"id": "abcd1234", "profile":{"email": "someone@example.com"}}  );