2013-04-13 14 views

cevap

5

Genel nesneye bir başvuru atmanız ve sonra stringify yöntemini almanız gerekir;

Local<Object> obj = ... // Thing to stringify 

// Get the global object. 
// Same as using 'global' in Node 
Local<Object> global = Context::GetCurrent()->Global(); 

// Get JSON 
// Same as using 'global.JSON' 
Local<Object> JSON = Local<Object>::Cast(
    global->Get(String::New("JSON"))); 

// Get stringify 
// Same as using 'global.JSON.stringify' 
Local<Function> stringify = Local<Function>::Cast(
    JSON->Get(String::New("stringify"))); 

// Stringify the object 
// Same as using 'global.JSON.stringify.apply(global.JSON, [ obj ]) 
Local<Value> args[] = { obj }; 
Local<String> result = Local<String>::Cast(stringify->Call(JSON, 1, args)); 
+0

Bazı şeyler görünüşte V8 API değişti: 1. hayır 'GetCurrent' yoktur ve genellikle kullandığınız izolattan küresel olsun' izolat-> GetCurrentContext() -> Genel() '. 2. 'String :: New()' dır ve genellikle 'String :: NewFromUTF8()' olmasını istersiniz. Bunun başka bir cevabı haklı çıkardığını düşünmeyin, ancak sizinkini güncelleştirirseniz arayabiliriz. – Stav

1

Düğüm API'lerinden bazıları OP'nin yayımlanmasından değiştirildi. Node.js sürüm 7.7.1'i varsayarsak, kod satırları boyunca bir şeye dönüşür;

std::string ToJson(v8::Local<v8::Value> obj) 
{ 
    if (obj.IsEmpty()) 
     return std::string(); 

    v8::Isolate* isolate = v8::Isolate::GetCurrent(); 
    v8::HandleScope scope(isolate); 

    v8::Local<v8::Object> JSON = isolate->GetCurrentContext()-> 
     Global()->Get(v8::String::NewFromUtf8(isolate, "JSON"))->ToObject(); 
    v8::Local<v8::Function> stringify = JSON->Get(
     v8::String::NewFromUtf8(isolate, "stringify")).As<v8::Function>(); 

    v8::Local<v8::Value> args[] = { obj }; 
    // to "pretty print" use the arguments below instead... 
    //v8::Local<v8::Value> args[] = { obj, v8::Null(isolate), v8::Integer::New(isolate, 2) }; 

    v8::Local<v8::Value> const result = stringify->Call(JSON, 
     std::size(args), args); 
    v8::String::Utf8Value const json(result); 

    return std::string(*json); 
} 

Temel olarak, kod, motordan JSON nesne alır nesnenin fonksiyonu stringify bir başvuru elde eder ve sonra da çağırır. Kod javascript ile aynıdır;

var j = JSON.stringify(obj); 

daha v8 bazlı alternatifler JSON sınıfı kullanılarak bulunmaktadır.

auto str = v8::JSON::Stringify(v8::Isolate::GetCurrent()->GetCurrentContext(), obj).ToLocalChecked(); 
v8::String::Utf8Value json{ str }; 
return std::string(*json); 
İlgili konular