Wazery
Wazery

Reputation: 15902

Extract specific string

I have the following QString that I want to extract only the access_token value which is "http%3a%2f%2fschemas.xmlsoap....." How to do that?

{"token_type":"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0","access_token":"http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=asdasr21321214a%2f%2fschemas.microsoft.com%2faccwresscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1347332993&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=sFqvp2a2xXc3VBdxYZ6xHQf%2fKkOydnuX6VK7A6Yf55k%3d","expires_in":"599","scope":"http://api.microsofttranslator.com"}

Upvotes: 0

Views: 667

Answers (3)

Valentin H
Valentin H

Reputation: 7458

Quick and dirty, only for demonstration of QString::section:

QString Data("{...you json data...}");
QString AccessToken = data.section("access_token\":\"",1).section("\"",0,0);

Consider: QString::section is slow and heavy, creating QStringList and converting tokens to RegExp in background. But I still do use it frequently in some cases.

Upvotes: 1

Ria
Ria

Reputation: 10347

Try this regex:

\"access_token\":\"([^\"]*)\"

explain:

( subexpression )
Captures the matched subexpression and assigns it a zero-based ordinal number.

[^ character_group ]
Negation: Matches any single character that is not in character_group. By default, characters in character_group are case-sensitive.

Upvotes: 1

mzelina
mzelina

Reputation: 71

Check out QJson at http://qjson.sourceforge.net/.

You can easily parse a string into tokenized attributes. From the usage page:

QJson::Parser parser;
QString json = "{your json above}";
bool ok;
QVariant result = parser.parse (json, &ok);
qDebug() << result["access_token"].toString();

Have fun.

Upvotes: 2

Related Questions