I am creating a console based on the v8 shell, I took an example of the code that replaced v8, and it works very well, but I am trying to convert the v8 :: object to its lowercase version (json), but have not found a way to do this.
Here is my sample code inside shell.cc:
v8::Handle test(const v8::Arguments& args) { v8::HandleScope handle_scope; const char* json; v8::String::Utf8Value strJson(args[0]); printf(ToCString(json)); if (args[0]->IsObject()) { printf("it an object\n"); } return v8::String::New(""); }
In the shell, I created a test.js file with this:
var a = { name: 'John' }; test(a);
and I get this after running js in the shell console:
[object Object] It an object
I want:
{ "name": "John" }
if i changed js code to:
var a = { name: 'John'} test(JSON.stringify(a));
it works very well, but I donβt want the user to know how to parse the javascript variable in json, and I donβt want to check every single input of the object and parse it manually.
Is there a way to execute the same statement inside shell.cc code in C? something like:
v8::Handle<v8::String> temp = JSON.parse(arg[0]);
update: This is how I handle this, but I need a cleaner way to do the same:
const char* toJson(const v8::Local<v8::Object>& obj) { std::stringstream ss; ss << "{"; v8::Local<v8::Array> propertyNames = obj->GetPropertyNames(); for (int x = 0; x < propertyNames->Length(); x++) { if (x != 0) { ss << ", "; } v8::String::Utf8Value name(propertyNames->Get(x)); ss << "\"" << ToCString(name) << "\":"; v8::Local<v8::Value> val = obj->GetInternalField(x); if (val->IsObject()) { ss << toJson(val->ToObject()); } else { ss << "\"" << ToCString(v8::String::Utf8Value(val)) << "\""; } } ss << "}"; const char* result = ss.str().c_str(); return result; } v8::Handle test(const v8::Arguments& args) { v8::HandleScope handle_scope; const char* json; v8::String::Utf8Value strJson(args[0]); if (args[0]->IsObject()) { char* json = toJson(args[0]);
Cross
source share