javascriptiosswiftiphonejavascriptcore

JavaScriptCore evaluateScript cannot handle objects?


I am working with JSContext and the rest of JavaScriptCore. Can anybody explain to me why evaluateScript fails in the second assertion?

let context = JSContext()!
let obj1    = context.evaluateScript("[{ 'first': 'Grace', 'last': 'Hopper', 'year': 1906 }]")
assert(obj1?.isArray ?? false)
let obj2    = context.evaluateScript(" { 'first': 'Grace', 'last': 'Hopper', 'year': 1906 } ")
assert(obj2?.isObject ?? false)

Why does wrapping an object in an array works, but the raw objects does not work?


Solution

  • As Pointy pointed out a script starting with { is evaluating as a block, instead of an object. This is the workaround for now:

    let obj2 = context.evaluateScript("[{ 'first': 'Grace', 'last': 'Hopper', 'year': 1906 }]")
    assert(obj2?.objectAtIndexedSubscript(0)?.isObject ?? false)
    

    Basically wrapping it in an array, and unwrapping the first object. Works fine