【问题标题】:Interpret 2 separate JSON return objects解释 2 个单独的 JSON 返回对象
【发布时间】:2017-10-24 12:14:43
【问题描述】:

我在登录后使用 oauth 后端生成有效令牌,但我返回 2 个单独的 json 对象,因为当我创建令牌并从我的数据库返回用户数据时,我无法将它们与 PHP 链接,所以我得到一个像这样的字符串:

{"id":"1","email":"test@test.com","username":"user","firstname":"john","lastname":"doe"} {"access_token":"d0f8...2a","expires_in":3600,"token_type":"Bearer","scope":null}

如您所见,我得到了 2 个单独的 JSON 对象,它们也都在一行上,所以我不能用新行分割,而且我觉得分割这些数据只会弄得一团糟

在 Angular 2 中,从中获取 2 个 JSON 对象的最佳方法是什么?

这是我返回数据的方式:

login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password).subscribe(
            (data) => {
                if(data) {
                    console.log(data);
                }
                /*this.authenticationService.token = (data.token)
                if(data.token) {
                    localStorage.setItem('currentUser', data.token);
                    this.loading = false;
                    this.router.navigate(['/user']);
                }else{

                }*/
            },  //changed
            (err)=> {
                console.log(err);
                this.error = 'Username or password is incorrect';
                this.loading = false;},
            ()=>console.log("Done")
        );
    }

【问题讨论】:

  • 因为当我创建令牌并从我的数据库返回用户数据时我无法将它们与 PHP 链接,所以我得到了这样的字符串?代码是写在哪里的?

标签: php json angular


【解决方案1】:

您应该将这 2 个对象包装到数组或对象中,然后从您的服务器返回,这样您将获得有效的 JSON。

返回如下内容,而不是您的有效负载:

{
  "profile": {"id":"1","email":"test@test.com","username":"user","firstname":"john","lastname":"doe"},
  "auth": {"access_token":"d0f8...2a","expires_in":3600,"token_type":"Bearer","scope":null}
}

在你的 PHP 中有这样的东西:

// your current object representation of the JSON you are sending
$profile = ...;
$auth = ...;

$wrapper = new \stdClass;
$wrapper->profile = $profile;
$wrapper->auth = $auth;

$json = json_encode($wrapper);

// and just return the $json variable instead of concatenating those 2

要解决您在 cmets 中提到的问题,您可以使用输出缓冲:

ob_start(); // start gathering the output of `echo`
$server->handleTokenRequest(OAuth2\Request::createFromGlobal‌​s())->send(); // call the method that echoes
$auth = ob_get_clean();

// now you have the JSON string in $auth
$wrapper = new \stdClass;
$wrapper->profile = $profile;
$wrapper->auth = json_decode($auth); // use `json_decode` to parse it to object

$json = json_encode($wrapper); // create the JSON again

最后一个注释 - 这绝对是正确的方法,但要回答您关于解析两个对象的原始问题 - 您可以简单地拆分 }{ 上的字符串,除非您连接更多,否则不会出现在有效 JSON 中其中。

var doubleJSON = '{"id":"1","email":"test@test.com","username":"user","firstname":"john","lastname":"doe"} {"access_token":"d0f8...2a","expires_in":3600,"token_type":"Bearer","scope":null}';

var temp = doubleJSON.split(/\}\W+\{/); // use regexp, that allows white space character between `}` and `{`
var profile = JSON.parse(temp[0] + '}'); // add the `}` character to the end, that is missing because of the split call
var auth = JSON.parse('{' + temp[1]); // add the `{` character to the front, that is missing because of the split call

console.log(profile);
console.log(auth);

【讨论】:

  • 我想这样做,这是我的第一个想法,但我不确定如何将这个调用 if($userclass->validUser($email,$password)) { $server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send(); }(该调用回显一个 json 对象)并将其与我的结果结合起来
  • 我明白了。您有 2 个选项,一个是使用 php.net/manual/en/book.outcontrol.php,另一个是将这 2 个内容拆分为 2 个请求。
  • 我添加了带有输出缓冲的示例 + 也是一种解析这 2 个 JSON 的方法
【解决方案2】:

如果你只是可以在代表两个对象的两个字符串之间放一个额外的字符(对于鸡蛋:';'),你可以通过这个字符拆分来解析它:

var str = '{"id":"1","email":"test@test.com","username":"user","firstname":"john","lastname":"doe"};{"access_token":"d0f8...2a","expires_in":3600,"token_type":"Bearer","scope":null}';

var str = '[' + str.split(';').join(',') + ']';

var objects = JSON.parse(str);
var obj1 = objects[0];
var obj2 = objects[1];
console.log("obj1: ", obj1);
console.log("obj2: ", obj2);

如果你想玩 ES6,它会更短:

var str = '{"id":"1","email":"test@test.com","username":"user","firstname":"john","lastname":"doe"};{"access_token":"d0f8...2a","expires_in":3600,"token_type":"Bearer","scope":null}';
var [obj1, obj2] = str.split(";").map(el => JSON.parse(el));
console.log("obj1: ", obj1);
console.log("obj2: ", obj2);

【讨论】:

  • OP 说他们不是...... they are all on one line aswell ...
猜你喜欢
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多