How to get JavaScript Object from '[object Object]' string? - javascript

I'm working on a WebView app in React Native, and I need to handle the messages sent by website (using postMessage) using the onMessage callback. As per the docs -
window.postMessage accepts one argument, data, which will be available
on the event object, event.nativeEvent.data. data must be a string.
But the the string (event.nativeData.data) that I am getting in my onMessage() function is '[object Object]' which I know is the result of calling toString() method on an Object.
Is there any way to get back the JavaScript Object obj from the resulting String obtained using obj.toString() ?
I tried JSON.parse() but it only gives the error as shown in the attached image below.
Thanks !

Is there any way to get back the JavaScript Object obj from the resulting String obtained using obj.toString() ?
No. The data in the object simply does not appear in the string.
You can tell this just by looking at the string! There is nothing that either resembles the original data nor which looks like an encoded something.
If you want to preserve the data, then use JSON.stringify to convert it to a string instead of converting it with .toString().

Related

JSON Parse error: Unexpected identifier "undefined" when trying to parse an object from an array (React-Native)

I have created a way to store data the way I want in AsyncStorage. This includes:
Reading a variety of input (various arrays)
Storing the input in a local this.state.object that houses multiple arrays
Stringifying this.state.object
Storing the stringified object in a temp array
Assigning the array with all objects to another state, this.state.allObjects
Stringifying 'this.state.allObjects'
Storing stringified array in AsyncStorage
The end goal of all of this is to have an array of objects that each represent a very different instance of the same type (with different parameters etc.). It may not be the most elegant approach, but it seems to store and load fine.
The issue arises when I try to parse anything from this.state.allObjects[x]. Or rather, it only occurs when I need to access it in a case that is NOT right after I load it.
During my loadFromAsync function, I am perfectly able to execute this.state.allObjects = JSON.parse(fromAsync); to get the array of stringified objects and then var display = JSON.parse(this.state.allObjects[0]).name to retrieve the name of the first parsed object of the array.
Any time outside of this function when I try to call var display = JSON.parse(this.state.allObjects[0]).name or even simpler <Text>{JSON.parse(this.state.allObjects[0]).name}</Text> I receive the following errors:
when running
const parse = JSON.parse(this.state.allObjects[0]);
//JSON Parse error: Unexpected identifier "undefined"
console.log(parse.name);
and when running
const parse = JSON.parse(this.state.allObjects[0]).name;
//JSON Parse error: Unexpected identifier "undefined" + null is not an object (evaluating 'JSON.parse(this.state.allObjects[0]).name
console.log(parse);
and lastly while running
const parse = JSON.parse(this.state.allObjects);
//JSON Parse error: Unexpected EOF + JSON Parse error: Unexpected token ','
I assume that this.state.allObjects changes somewhere within my code, or appends an extra } somewhere, though it really shouldn't. When I display this.state.object and this.state.allObjects[0], their format is exactly the same visually. Adding more objects to this.state.allObjects and displaying each stringified component also works; it is just a matter of actually parsing these components that is not working outside the original load function.
I am extremely stuck. Any advice is appreciated. If I need to change my datatype, that's fine. It's just a bit annoying to have come this far with a stringified array of stringified objects holding arrays and not be able to parse it.
Because this.state.allObjects Already JSON object.
Try JSON.stringify()

What object has a String representation of `{name=value}` in JavaScript?

I receive a complex value in JavaScript (inside the JDK Nashorn engine), that I have to interact with. That value prints to the console as {shown=true}. When I say typeof value I receive object as an answer. When I say Object.keys(value); I receive a TypeError: {shown=true} is not an Object in .... Whey I say value.shown or value["shown"] I always receive a null.
What is type is this mysterious object, and how do I access the value of the "shown" property correctly?
Unfortunately, it is not easy to create a simple example and I cannot debug interactively... Any help is highly appreciated!
Edit:
JDK is JavaSE-1.8.
Calling JSON.parse(value); results in
javax.script.ScriptException: SyntaxError: Invalid JSON: <json>:1:1 Expected , or } but found s
{shown=true}
^
Assuming what you got is a Java object, you should be able to call value.getClass() to get its Java class.
From its string representation, it might be an instance of java.util.HashMap or similar. If so, you should be able to access the value of the "shown" property via value.get("shown").

How to get the value in result.rows[0] as a string?

I am querying a Cassandra database using Node.js, and receiving result. I can access each element of the result with result.rows[0] etc.
However, I am currently trying to do data processing of the result in Javascript. I tried to convert result.rows[0] to String with result.rows[0].data.toString() but this returned error Cannot read property toString of undefined.
I know that I do indeed have data in my result.rows[0]. What is the problem in this situation, and how would I go about acquiring the String contained in result.rows[0]? I have also tried getting toString() of result yet that is returning [object Object].

Can i save a javascript object with cookies?

I have been working on a project that uses a object to maintain a conversation with the user. However if what has been asked by the user is not in this object. The user is prompted for what should the "AI" answer. The problem is that I can't save this object, so when the user closes the tab or reloads it everything that the "AI" has learned disappears. I've tried using localStorage.setItem('dictionary', JSON.stringify(dictionary)) (dictionary is the object) However it gave me "[object Object]". So i was wondering if there was anyway I could use cookies instead?
after you store your object you need to use it like this,
var dictonaryParsed = JSON.parse(localStorage.getItem('dictionary'));
this will fix your problem, this is because localStorage.setItem() will use the toString() method from the prototype chain, and you will get this [object Object].
This is because everything is converted to string before stored to the key,value pair database(localStorage).
With stringify method that you are using the object will be prepared for the JSON.parse() method if not used you will get something like this "{"a":10}", so you need to Parse your object before using it. If you try to parse not stringyfied object you will get error.
the localstorage you use has no problem,did you alert the object and you see the '[object Object]'?

Parsing incoming JSON in JavaScript - what happens to the "extended parameters"?

I am attempting to parse the incoming JSON from XBMC (Eden Beta v3), an example string from XBMC is as follows:
{"jsonrpc":"2.0","method":"Player.OnPlay","params":{"data":{"item":{"type":"movie"},"player":{"playerid":1,"speed":1},"title":""},"sender":"xbmc"}}
I am using json2.js from https://github.com/douglascrockford/JSON-js/blob/master/json2.js to give me the JSON.parse and JSON.stringify functions in my application.
I am using the parse function in my code like this
var temp = JSON.parse(data);
Which is working fine for the first two properties, "jsonrpc" and "method"... so I can access those like this
temp.method
returns "Player.OnPlay"
temp.jsonrpc
returns "2.0"
However, if you look at the string sent by XBMC, it also contains what they refer to as "extended parameters" or "params", I cannot seem to track down what the JSON parser is doing with the rest of the message, or how I can access them in similar ways as the first two properties. If I try
params = temp.params
or any other way of accessing the params property, I get an Undefined error as there is no such property in the JSON object... I hope this is clear enough for someone to take a stab at helping me out. Will provide any extra info needed...
Thanks
The value of params in the JSON data is an object, so you have to access the sub-properties of that.
temp.jsonrpc
temp.method
temp.params["data"]["item"]["type"]
temp.params["data"]["player"]["playerid"]
temp.params["data"]["player"]["speed"]
temp.params["data"]["item"]["title"]
temp.params["sender"]

Categories