String Split in C++

Asked

Viewed 168 times

1

Folks I’m looking for a split on the following String in C++

[
 {
  "Nome":"Gabriel",
  "idade": 23
 }
]

I’m doing it this way...

I receive this json through a query get and storing in a string to power the split (OBS: I don’t know if I would have any better way to do this)

run = json.split(","); 

json[0] is returning my first element with the [ and {

[ { "Nome":"Gabriel"

how do I get only the name gabriel or even the value 23 of age

NOTE: I am using Qt Creator 4.8 where it is not yet supported to work with json, unfortunately.

  • 4

    https://github.com/nlohmann/json

  • 5

    QT: https://doc.qt.io/qt-5/json.html

  • split ? Doesn’t mean parse ? As a general rule the action of interpreting a JSON is called parse.

  • This, however, in the Qt environment does not give me support to work with json. One way I found though I don’t know if it’s the best way to do it, was to take this json and put it in a Qstring and from that I do the split Qt only of json support in version 5

1 answer

0

There are some JSON libraries for C++, but if you don’t want to use it, you can make a small parser:

string strJSON = string("..aqui vai o json.")
string strProp = string("\"idade\":");
int szJSON = strJSON.size();

//encontra a posição de inicio da propriedade:
int pos = strJSON.find(strProp);
if (pos == std::string::npos)
    throw string("propriedade idade não encontrada");
pos+=strProp.size();//pula a parte que é igual ao strProp, logo antes do ':'

//pular caracteres não numéricos
while(pos<szJSON && (strJSON[pos] < '0' || strJSON[pos] > '9')) pos++;

//salva posição onde inica os números 
int startPos = pos;

//pular caracteres numéricos apenas
while(pos<szJSON && (strJSON[pos] > '0' || strJSON[pos] < '9')) pos++;

//se o ponteiro inicial é igual ao final, os chegarão dois estão no final da string sem encontrar nenhum numero
if (startPos == pos)
    throw string("sequencia numérica não encontrada");

//pegar a string com caracteres numéricos..
string strIdade = strJSON.substr(startPos, pos - startPos);
//converte-la para inteiro
int idade = atoi(strIdade.c_str());

*Obs.: this not valid JSON code only takes the first numeric sequence after the chosen property.

*Obs 2.: don’t forget to #incluide <string> and using namespace Std

Browser other questions tagged

You are not signed in. Login or sign up in order to post.