解释2个单独的JSON返回对象

时间:2017-10-24 12:14:43

标签: php json angular

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

  

{ “ID”: “1”, “电子邮件”: “test@test.com”, “用户名”: “用户”, “姓名”: “约翰”, “姓”: “DOE”}   { “的access_token”: “d0f8 ... 2A”, “expires_in”:3600, “token_type”: “承载”, “范围”:空}

正如你所看到的,我得到了两个独立的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")
        );
    }

2 个答案:

答案 0 :(得分:1)

您应该将这两个对象包装到数组或对象中,然后从服务器返回,这样您就拥有了有效的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

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

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);




答案 1 :(得分:0)

如果您只是在代表两个对象的两个字符串之间添加一个额外的字符(对于egg:'; '),您可以通过拆分此字符来解析它:

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);