Tencent / rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API
http://rapidjson.org/
Other
14.19k stars 3.53k forks source link

Assertion `IsObject()' failed. #2031

Closed Norbiros closed 2 years ago

Norbiros commented 2 years ago

Hi! This is my json file:

{
    "hello": "world",
    "t": true ,
    "f": false,
    "n": null,
    "i": 123,
    "pi": 3.1416,
    "a": [1, 2, 3, 4]
}

And this is my C++ file:

#include "../include/rapidjson/filereadstream.h"
#include "../include/rapidjson/document.h"
#include <cstdio>

using namespace rapidjson;
using namespace std;

int whatIsThis() {
  FILE* fp = fopen("games/a.json", "r"); // non-Windows use "r"

  char readBuffer[65536];
  FileReadStream is(fp, readBuffer, sizeof(readBuffer));

  Document d;
  d.ParseStream(is);

  fclose(fp);

  cout << d["hello"].GetString() << endl;

  return 0;
}

When I execute this code, I get this error:

main: games/../include/rapidjson/document.h:1344: rapidjson::GenericValue<Encoding, Allocator>::MemberIterator rapidjson::GenericValue<Encoding, Allocator>::FindMember(const rapidjson::GenericValue<Encoding, SourceAllocator>&) [with SourceAllocator = rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>; Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>; rapidjson::GenericValue<Encoding, Allocator>::MemberIterator = rapidjson::GenericMemberIterator<false, rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator> >]: Assertion `IsObject()' failed.

I looked for a lot of ideas how to fix it, but it just does not work! I think it is problem with code, not with json data...

Please, if anyone know how to fix it, help :) You can view whole code here: https://github.com/Norbiros/ConsoleGames.git

miloyip commented 2 years ago

You may firstly check the return code of ParseStream().

Norbiros commented 2 years ago

You may firstly check the return code of ParseStream().

I found it here.

It returns The document itself for fluent API.. And I am using it as document for example d["hello"]...

Also, it is copied example from docs. I didn't change anything, so how I can get this error?

miloyip commented 2 years ago

I mean, there may be parsing error or reading error during the parsing process. You can check d.HasParseError() and d.GetParseError(). If the parsing is fail, the document will be a JSON null type.

Norbiros commented 2 years ago

Thanks you very much! Everything works great now 😄

colin-de commented 1 year ago

hi, could you please share your method to solve this issue? thx!

Norbiros commented 1 year ago

hi, could you please share your method to solve this issue? thx!

I don't remember my solution, but here is my source code: https://github.com/Norbiros/ConsoleGames/blob/main/games/what_is_this.cpp

Maybe it helps :)