I have this simple variable which I am trying to extract data from. I've parsed it successfully to a json object and tried to print a value based on it a key. But all it says is "undefined". This example I provided is actually a snippet of the json I am trying to manipulate. The full file is actually a json object where one of the elements contains an array of many json objects (these are the ones I ultimately have to access). I have watched countless tutorials and have followed them exactly, but none seem to have this issue.
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
JSON.parse(x);
console.log(x.status);
Can anybody suggest something I may be doing wrong? Thank you!
JSON.parse Return value
The Object, Array, string, number, boolean, or null value
corresponding to the given JSON text. - MDN
You have to assign the parsed result to some variable/constant from where you can use later that parsed value and then use that variable to extract data as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
const parsedData = JSON.parse(x);
console.log(parsedData.status);
or you can directly get value one time after parsed as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
console.log(JSON.parse(x).status);
Related
I have JSON data in the following structure, and I'm trying to parse it in order to work with the data using javascript.
JSON Data
{
"FirstItem": {
"id": 1,
"type": "foo",
"colours": ["blue", "black", "green"],
"reviews": {
"positive": ["The best", "unbelievable", "Awesome"],
"negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"],
"neutral": ["OK", "Meh"]
}
},
"SecondItem": {
"id": 2,
"type": "bar",
"colours": ["red", "white", "yellow"],
"reviews": {
"positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"],
"negative": ["Terrible", "Shocking", "abysmal"],
"neutral": ["OK", "Standard", "Vanilla"]
}
}
}
I am trying to parse this using JSON.parse(), however this returns the following error:
JSON.parse: unexpected character at line 1 column 2 of the JSON data
I have previously worked with this same JSON structure using C#, and had to deserialise this into a dictionary - information can be found on this post
Question
How can I parse this JSON into a javascript object, which will allow me to loop and evaluate each item?
JSON is Javascript Object with double quoted key like what you have in sample. So you don't need to parse it again, see this for explanation. You can access data from it using its key or if in case you want to get reviews from SecondItem, you can access it with :
SecondItem.reviews
or
SecondItem['reviews']
Apparently you are trying to parse an already parsed object
x = {A:1}; // A javascript object
JSON.parse(x); // Error
this happens because JSON.parse will convert the object to a string first, getting "[object Object]" and then will try to parse this string.
I have a "deep" JSON string that I need to pass as GET vars in a URL. It looks like the following:
{
"meta": {
"prune": true,
"returnFields": ["gf", "gh", "gh", "rt"],
"orient": "split"
},
"indicators": [{
"type": "beta",
"computeOn": "gf",
"parameters": {
"timeperiod": 5,
"nbdevup": 2,
"nbdevdn": 2,
"matype": 0
}
}, {
"type": "alpha",
"computeOn": "gf",
"parameters": {
"timeperiod": 30
}
}]
};
When encoding using jQuery.param, the result is as follows:
var recursiveEncoded = jQuery.param(body);
console.log(recursiveEncoded);
meta%5Bprune%5D=true&meta%5BreturnFields%5D%5B%5D=gf&meta%5BreturnFields%5D%5B%5D=gh&meta%5BreturnFields%5D%5B%5D=gh&meta%5BreturnFields%5D%5B%5D=rt&meta%5Borient%5D=split&indicators%5B0%5D%5Btype%5D=beta&indicators%5B0%5D%5BcomputeOn%5D=gf&indicators%5B0%5D%5Bparameters%5D%5Btimeperiod%5D=5&indicators%5B0%5D%5Bparameters%5D%5Bnbdevup%5D=2&indicators%5B0%5D%5Bparameters%5D%5Bnbdevdn%5D=2&indicators%5B0%5D%5Bparameters%5D%5Bmatype%5D=0&indicators%5B1%5D%5Btype%5D=alpha&indicators%5B1%5D%5BcomputeOn%5D=gf&indicators%5B1%5D%5Bparameters%5D%5Btimeperiod%5D=30
Which is decoded to the following:
var recursiveDecoded = decodeURIComponent( jQuery.param(body) );
console.log(recursiveDecoded);
meta[prune]=true&meta[returnFields][]=gf&meta[returnFields][]=gh&meta[returnFields][]=gh&meta[returnFields][]=rt&meta[orient]=split&indicators[0][type]=beta&indicators[0][computeOn]=gf&indicators[0][parameters][timeperiod]=5&indicators[0][parameters][nbdevup]=2&indicators[0][parameters][nbdevdn]=2&indicators[0][parameters][matype]=0&indicators[1][type]=alpha&indicators[1][computeOn]=gf&indicators[1][parameters][timeperiod]=30
If just using a serialized string result on the server leaves the string as the key in a key value pair:
"query": {
"{\"meta\":{\"prune\":true,\"returnFields\":[\"gf\",\"gh\",\"gh\",\"rt\"],\"orient\":\"split\"},\"indicators\":[{\"type\":\"beta\",\"computeOn\":\"gf\",\"parameters\":{\"timeperiod\":5,\"nbdevup\":2,\"nbdevdn\":2,\"matype\":0}},{\"type\":\"alpha\",\"computeOn\":\"gf\",\"parameters\":{\"timeperiod\":30}}]}": ""
},
My backend processing is done with Python. What modules exist to convert the above result to a dict resembling the original object?
Well, since we hashed it out in the comments, I'll post the answer here for posterity.
Use a combination of JSON.stringify on the JavaScript side to serialize your data structure and json.loads on the Python side to deserialize it. Pass the serialized structure as a query string parameter ("query" in your example) and then read the value from that query string parameter in Python. Huzzah!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I have some json being returned from a jquery ajax function.
Here is an example of said json:
var b =
{
"SelectByUserResult": [{ "DateAdded": "/Date(1357300130930+0000)/", "Deleted": false, "FileExtension": "jpg", "Filename": "e5d1ee90-f3c0-4dd7-9996-d1725a1fc031.jpg", "Height": 768, "Id": 955, "IsBpMember": true, "OriginalFilename": "Tulips.jpg", "SessionId": "277d31bf-84e1-4678-ad66-e7b332936219", "Title": "New image", "TotalRecords": 16, "UserId": "ded98560-61d0-42f2-944e-30280d54e94b", "Width": 1024}]
}
I have other ajax functions which return similar json in a similar structure, the only difference is the object 'SelectByUserResult' might be changed to 'SelectByIdResult' or 'SelectByNameResult'.
So in my ajax function (in the success function) I would do this to access the json b.SelectByUserResult
I want to be able to access that object but without specifying the name (as it's not always known). How would I go about doing that? Thanks
My funny variant (maybe not the best). It will return the first property of the object, I guess this is what you need.
function getFirstProp(obj) {
for (var i in obj) return obj[i];
}
Usage:
console.log(getFirstProp(b));
I have the following JSON object:
[
{
"comments": [
{
"created_at": "2011-02-09T14:42:42-08:00",
"thumb": "xxxxxxx",
"level": 1,
"id": 214,
"user_id": 41,
"parent_id": 213,
"content": "<p>xxxxxx</p>",
"full_name": "xx K"
},
{
"created_at": "2011-02-09T14:41:23-08:00",
"thumb": "xxxxxxxxxxxxx",
"level": 0,
"id": 213,
"user_id": 19,
"parent_id": null,
"content": "<p>this is another test</p>",
"full_name": "asd asd asd asd asd"
}
],
"eee1": "asdadsdas",
"eee2": "bbbbb"
}
]
This is coming from a $.ajax request, in success I have....
success: function (dataJS) {
console.log(dataJS);
console.log(dataJS[eee1]);
console.log(dataJS.comments);
}
Problem is I can't get access to the items in the JSON object, even though dataJS does show correctly in the console. Ideas?
That's because your base object is an array as well.
console.log(dataJS[0].comments[0]);
I suspect that would work
the JSON you have coming back is actually an array itself, so...
dataJS[0].comments[0].created_at
will be 2011-02-09T14:42:42-08:00, etc...
Both dataJS and comments are arrays, and need indexes to access the appropriate elements.
The object being returned is itself an array, so to get to the first comment (as an example), this is how you would access it:
dataJS[0].comments[0]
console.log(dataJS);
console.log(dataJS[0].eee1);
console.log(dataJS[0].comments[0]);
Do something like this:-
var dataJS = [{"comments":[{"created_at":"2011-02-09T14:42:42-08:00","thumb":"xxxxxxx","level":1,"id":214,"user_id":41,"parent_id":213,"content":"<p>xxxxxx</p>","full_name":"xx K"},{"created_at":"2011-02-09T14:41:23-08:00","thumb":"xxxxxxxxxxxxx","level":0,"id":213,"user_id":19,"parent_id":null,"content":"<p>this is another test</p>","full_name":"asd asd asd asd asd"}],"eee1":"asdadsdas","eee2":"bbbbb"}];
var created_at = dataJS[0].comments[0].created_at;
Yes, as others have stated, the JSON is actually an Array (of a single Object). So you will need to reference an index.
Interestingly enough (to me), your result string does validate successfully as JSON. I assumed until now, that to be valid JSON, it had to be an Object (ie, {}).
JSON must be interpreted with eval function (after the obvious sanitization, see security considerations of eval). Are you sure your framework does that for you?
I'm trying to work with json-framework on iPhone to parse a json string.
When I'm calling this method:
NSDictionary *dictionary = [jsonString JSONValue];
I'm getting the error:
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key:
Options\" UserInfo=0x4b5f390 {NSUnderlyingError=0x4b5f320 \"Expected value while
parsing array\", NSLocalizedDescription=Object value expected for key: Options}"
According to this json validator [1]: http://www.jsonlint.com// my json is not valid. But is that so??
My json string looks like this:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary",
}
}
* Edited Json: (still brings up an error)
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary"
}
]
}
Your JSON is not valid.
It's because you can't create object instances within JSON. It's not a valid value.
new Date(2011, 0, 7, 12, 30, 0)
And you missed the closing array bracket. Everything else is ok.
remove the comma after ...Binary"
add a ] between the two } }.
Date cant be used like this, see How do I format a Microsoft JSON date? and http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_sidebarb
This is valid:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": "new Date(2011,0,7,12,30,0)",
"Type": "Binary"
}
]
}
You can't instantiate Date objects (or any objects) in a JSON string.
You need to have whoever's responsible for the code that emits this JSON change it to emit valid JSON. They're putting out something now that can't work with any JSON parser. Maybe they have a customized JSON consumer that can handle such things, but this isn't standard JSON.
If I were you, I'd have them put the string of the current date into that field (so: "2011-07-01 12:30:00") and then parse that in your obj-cusing NSDateFormatter.
If whatever puts out that JSON isn't something you can change, you can always modify it locally before feeding it to the JSON library. It's just a string, nothing magical.