すずねーう
すずねーう10mo ago

How do I make Objects, Maps, etc. in rusty_v8 into easy-to-understand String?

Hello. I wrote the following code in rusty_v8
let isolate = &mut v8::Isolate::new(Default::default());

let mut client = InspectorClient::new();
let mut inspector = V8Inspector::create(isolate, &mut client);

let scope = &mut v8::HandleScope::new(isolate);
let context = v8::Context::new(scope);
let scope = &mut v8::ContextScope::new(scope, context);

inspector.context_created(context, 1, StringView::empty());

let mut result_strings: Vec<String> = Vec::new();

v8::String::new(scope, &code)
.map(|code| {
println!("code: {}", code.to_rust_string_lossy(scope));
code
})
.and_then(|code| v8::Script::compile(scope, code, None))
.and_then(|script| script.run(scope))
.and_then(|value| value.to_string(scope))
.iter()
.for_each(|value| {
result_strings.push(value.to_rust_string_lossy(scope));
});

let result = result_strings.join("\n");
println!("{}", result);
let isolate = &mut v8::Isolate::new(Default::default());

let mut client = InspectorClient::new();
let mut inspector = V8Inspector::create(isolate, &mut client);

let scope = &mut v8::HandleScope::new(isolate);
let context = v8::Context::new(scope);
let scope = &mut v8::ContextScope::new(scope, context);

inspector.context_created(context, 1, StringView::empty());

let mut result_strings: Vec<String> = Vec::new();

v8::String::new(scope, &code)
.map(|code| {
println!("code: {}", code.to_rust_string_lossy(scope));
code
})
.and_then(|code| v8::Script::compile(scope, code, None))
.and_then(|script| script.run(scope))
.and_then(|value| value.to_string(scope))
.iter()
.for_each(|value| {
result_strings.push(value.to_rust_string_lossy(scope));
});

let result = result_strings.join("\n");
println!("{}", result);
Numbers such as 1+1 and strings such as "Hello!" are output correctly, but objects such as { a: 1 } are displayed as [object Object]. Is there any way to fix this?
2 Replies
Deno AI Helper
Deno AI Helper10mo ago
The issue you're encountering is due to the fact that the to_string method in V8 converts JavaScript objects to their default string representation, which for objects is [object Object]. To get a string representation of an object that includes its properties, you would typically use JSON.stringify in JavaScript. However, the rusty_v8 crate does not provide a direct way to call JavaScript functions like JSON.stringify. The documentation does not provide a clear solution for this specific issue. However, you might consider creating a JavaScript function in your runtime that uses JSON.stringify and then call this function from Rust. Please note that this advice is not explicitly supported by the documentation and might require additional research and testing.
すずねーう
すずねーう10mo ago
JSON.stringify can't handle Map or something class