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

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"]

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()

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

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().

Access fields in an array contained in a model

I have some JavaScript code that needs to be able to access fields of an array of objects that is contained within my model. I currently have this:
var model = #Html.Raw(Json.Encode(Model));
for(var i = 0; i < model.testobject.length; i++) {
console.log(model.testobject[i]);
}
Which prints out the fields within each object of testobject. But say I have a field, ID, in my testobject class. How do I then access that? Doing this:
console.log(model.testobject[i].ID);
Does not work. Do I have to somehow encode that specific instance of testobject before accessing it's fields?
And yes, before anyone says it I know this should be contained within the controller. As it currently stands though, that's not possible for this project.
This is the general structure of what is printed out:
Object {field: value}
Edit:
I attempted to use JSON.stringify on my model.IdentifiApprovalConfigurations and it seems I got a little close to reaching my solution. This is what it looks like now:
console.log(JSON.stringify(model.testobject[i]).ID);
However, this prints out undefined.
Edit 2:
Oops, seems the ID field I'm trying to access isn't being populated before I send them to my view which is my own issue. JSON.stringify works though, and I understand why it wasn't working earlier.
Final edit:
JSON.parse(JSON.stringify(model.testobject[i])).Value
I had to stringify and then parse my JSON to access the value.
As I'm still starting out with web development, I forgot that I needed to convert my object into a JSON object. This:
JSON.parse(JSON.stringify(model.testobject[i])).Value
Is the final piece of code that allows me to stringify an object, parse the JSON and then access fields within that object.

JavaScript json value

I have a JSON var response (See below) but I can't retreive the value of "reputation" using response.users[0].reputation. I am in Dashcode and it says in error Result of expression response.users[unknown] is not an object. What is the correct syntax?
edit: The variable is dynamically loaded from a XMLHttpRequest. A static var with same json is working.
I guess from XMLHttpRequest you recieve string but not json object, so you need parse it first in order to get json object, for example using JSON.Parse or jQuery.parseJSON and response.users[0].reputation should work.
The JSON is fine. I just checked it and "response.users[0].reputation". (Second pair of eyes and all that.)
I would be more concerned about the "unknown" in "response.users[unknown]". It doesn't look like you are requesting the 0th index of the array "users". Something's going wrong there.
Personnally when i test the syntax of your Json, it is correct :
http://www.jsonlint.com
I have just deleted the comment "//need to get its value".
Your code works for me as you have done it. Maybe you are not assigning the variable correctly (var response = {"total": 1, etc...) or have a typo somewhere

GoogleAppEngine JSON object using javascript

I want to create a dictionary containing array and send it to GAE using jquery's ajax request.
something like- {'a':'text', 'b':'othertext','c':['texta','textb']} which I'm creating manually.
I am able to receive and process a and b using self.request.get on GAE but not the c.
Is there any other way to create JSON object in js? Please suggest whats wrong in this method.
You're not really sending JSON to the server. When you pass the object to jQuery.ajax (or the get/post wrappers), it will be serialized into GET or POST variables, not sent as JSON, so your object would be converted into something like this:
a=text&b=othertext&c[]=texta&c[]=textb
If you want to pass the entire object as JSON, you can convert it yourself by calling JSON.stringify (you will need to include json2.js for browsers that don't support the JSON object natively). Then you can wrap the JSON-encoded string in a map with whatever name you want:
jQuery.post(url, { json: JSON.stringify({a:'text', ...}) }, ...);
On the server side, you can access the JSON text by calling self.request.get("json"). Then you would have to parse the JSON string to extract the values. I don't know much about Python, but apparently you just need to import django.utils.simplejson and call simplejson.loads(json).
Presumably, GAE's self.request.get is not able to serialize a complex object like a string array into a GET request format (?a=text&b=othertext...).
One workaround, although perhaps not a very neat one, would be to serialize the value to JSON yourself, and pass that:
var jsonObj = {
'a':'text',
'b':'othertext',
'cJSON': JSON.stringify(['texta', 'textb'])
};
... and then of course you'd have to deserialize cJSON at the receiving end.
You're actually sending urlencoded request parameters, not JSON. JQuery is probably encoding the list as multiple values for the same parameter, which means you can access it using self.request.get_all, which will return a list - self.request.get will only return the first value.

Categories