How to parse JSON in an embedded v8?
c++, json, v8
Solution
You can use JSON Parse function exposed through API:
v8::Local<v8::String> str; // some string
v8::Local<v8::Value> result = v8::JSON::Parse(str);
Newer versions of V8 provide `EscapableHandleScope` you need to use to return handle from function:
v8::EscapableHandleScope scope(isolate);
return scope.Escape(value);
This
if (value->IsEmpty()) { // CRASHES HERE.
should probably be
if (value.IsEmpty())
Hope this helps.
Problem
I am trying to Parse JS in my embedded V8 application and I get a SIGSEGV always. I am not sure what is happening. My code to parse json, ``` v8::Handle<v8::Value> FromJSONString( v8::Handle<v8::Value> json_string) { v8::HandleScope scope; v8::Handle<v8::Context> context = v8::Context::GetCurrent(); v8::Handle<v8::Object> global = context->Global(); v8::Handle<v8::Value> JSON_value = global->Get(v8::String::New("JSON")); if (!IsObject(JSON_value)) { return scope.Close(v8::Undefined()); } v8::Handle<v8::Object> JSON = JSON_value->ToObject(); v8::Handle<v8::Value> JSON_parse_value = JSON->Get(v8::String::New("parse")); if (JSON_parse_value.IsEmpty() || JSON_parse_value->IsNull() || JSON_parse_value->IsUndefined() ||!JSON_parse_value->IsFunction()) { return scope.Close(v8::Undefined()); } v8::Handle<v8::Function> JSON_parse = v8::Handle<v8::Function>::Cast(JSON_parse_value); return scope.Close(JSON_parse->Call(JSON, 1, &json_string)); } ``` The specific site which crashes => ``` bool extractSource(std::string* source, std::string& body) { v8::HandleScope scope; // this is needed and clears the memory if (body.empty()) { return false; } v8::Handle<v8::Value> value = v8_server_utils::FromJSONString(body); if (value->IsEmpty()) { // CRASHES HERE. return false; } if (value->IsNull()) { return false; } if (value->IsUndefined()) { return false; } if (!value->IsObject()) { return false; } auto object = value->ToObject(); auto source_key = v8::String::New("source"); if (object.IsEmpty() || object->IsNull() || object->IsUndefined() || !object->Has(source_key)) { return false; } auto source_obj = object->Get(source_key); *source = v8_server_utils::JSStringToCString(source_obj->ToString()); return true; } ```