I have the following json, I don't have any control over this output unfortunately.
{
"questions": {
"9733": {
"text": "Star Trek or Star Wars?",
"answers": {
"41003": "Star Trek",
"41004": "Star Wars",
"41005": "Neither is superior in my opinion; both great in their own ways",
"41006": "Not a fan",
"41007": "I don't have an opinion on this"
}
},
"25272": {
"text": "Which of these summer movies are you looking forward to the most?",
"answers": {
"99545": "World War Z",
"99546": "Monsters University ",
"99547": "White House Down",
"99548": "Man of Steel",
"99549": "Lone Ranger",
"99550": "The Wolverine"
}
},
"27547": {
"text": "Should the U.S. attack Syria?",
"answers": {
"107453": "Yes",
"107454": "No"
}
}
}
}
I am using json.parse to parse this. To get the text of the first question I would normally do something like this.
var jsonData = JSON.parse(data);//Where data = the json above
console.log(jsonData.questions.9733.text);//Obviously this fails
However javascript doesn't like that number in there obviously. How would you recommend accessing the text of the first question? I would prefer the json to be setup better with in an array of questions instead. Unfortunately I don't have any control over the output of this JSON.
I'm also not going to be aware of the what the keys are as they come across, but thats a whole other issue. I'm willing entertain any suggestions on how to parse this thing as I've never had to parse such a strange JSON output.
You need to use bracket notation:
console.log(jsonData.questions["9733"].text);
But because the value inside the brackets will be automatically converted a string, this would also work:
console.log(jsonData.questions[9733].text);
Note however, that using non-strings is as property names generally bad form and could lead to some subtle problems, e.g. if the property name was "001", then [001] would not work.
Why don't you try?
jsonData["questions"]["9733"]
How to access a numeric property?
I believe you can access the data via same syntax as in an array:
console.log(jsonData.questions[9733].text);
If you have to use numbers as keys... you can access them like this:
var text = jsonData.questions["9733"].text;
Edit: You can also access it with the number 9733. It doesn't have to be a string. Only needs to be a string if the key is non-numeric.
Try using Ason, If you are using Java 8. Gradle dependency compile 'org.arivu:ason:1.0.3'.
Java code as follows
Ason ason = new Ason();
Object json = ason.fromJson("<<JSON String!>>");
System.out.println(Ason.getJson(json, "questions.9733.text", null)):
Related
Hi recently in one of the interview i gone through this question.
How to minify json response
{
name: "sample name",
product: "sample product",
address: "sample address"
}
this what the question. I dont know how to minify and the process behind it. Can any one explain? please
Thanks in Advance.
You can parse the JSON and then immediately re-serialize the parsed object:
var myJson = `{
"name": "sample name",
"product": "sample product",
"address": "sample address"
}`;
// 'Minifying' the JSON string is most easily achieved using the built-in
// functions in the JSON namespace:
var minified = JSON.stringify(JSON.parse(myJson));
document.body.innerHTML = 'Result:<br>' + minified;
You'll have to perform the minification server-side to get an improvement in response size. I suppose most languages support an equivalent to the above snippet. For example, in php one might write this (if your server runs php, of course):
$myJson = '{
"name": "sample name",
"product": "sample product",
"address": "sample address"
}';
$minified = json_encode(json_decode($myJson));
The obvious way would be to strip the whitespace. Beside that you could also map the keys to something shorter like a, b, c.
Also if you want to be a jerk about it; you could tell them that valid json would have quotes around the keys. This seems to be a js object, not json.
Another method could be to create it as a array with implicit keys - basically the first item in the array maps to key 'name', the second to 'product' etc - this requires both sender and receiver of the message to know exactly the order of keys, so in your example it could be reduced to
["sample name","sample product","sample address"]
you can't really make it much shorter than that. If you have complex objects with sub keys you can use nested multidimensional arrays eg.
["sample name","sample product",["sample address1","sample address2"]]
This would be a good option for things like multiplayer game server networking where message size is a major factor for reducing latency and the client and server both know how the message is structured.
It's not strictly Json, but sometimes you have to use pragmatic solutions for performance.
First year # coding, this is very basic code style for js. Everything I look at to research for help is usually to complex for me to adapt into my basic code. Currently I've got this array I've created, and I'm trying to, in the end game, print out the "course_number, course_title, course_unit" object values onto a page. I'm also trying to modify them as well, but deleting or changing the values.
I'm just trying to call to CIS:0 right now and it's coming up as undefined. Do I need to use Object.create(CIS.___) or am I missing something here. I can't use the "new" function instead of Object.create
Tearing my hair out.
var cuesta = {
BUS_ED: {
CIS: [{
"course_number": "231",
"course_title": "Fundementals of Computer Science 1",
"Course Unit": "4"
},
{
"course_number": "201",
"course_title": "Intro to Computer Science",
"Course Unit": "3"
},
{
"course_number": "201",
"course_title": "Discrete Structures",
"Course Unit": "3"
}
],
}
};
alert(CIS[0]["course_number"]); // coming out as undefined
sorry for the mess, it has to stay in this type of structure because we haven't advanced further.
Z
You need to access the variable then all the separate elements in the data structure. You've almost got it. First cuesta then BUS_ED is an object, and then the rest you've got.
alert(cuesta.BUS_ED.CIS[0]["course_number"]);
be careful when you use the term undefined as in javascript 'undefined' is a speical value, so you had me a little confused. undefind is not the same as is not defined. / yes, javascript is weird.
Correct:
alert(cuesta.BUS_ED.CIS[0]["course_number"]);
var cuesta = { // Object
BUS_ED: { // new Object in object
CIS: [{ // array of objects in object.
Hope this helps.
I have the following standard Javascript assignment statement returned as the output form a webservice call. I need to get the JSON array object out of it and was wondering if I can somehow use NSRegularExpression to do that.
I have no control over the web service so it has to continue returning a Javacript assignment stmt as in the attached snippet below.
Can anyone suggest an objective-c code snippet that accomplishes this task? I could receive sub-array and sub hashes as part of the individual elements as well...
var collection = [
{
"id": "4444",
"name" : "Bill Smith",
"position" : "tester"
},
{
"id": "4444",
"name" : "Bill Smith",
"position" : "tester"
}
];
You can write something like this:
NSArray *myJSONArray = #[
#{
#"id": #"4444",
#"name" : #"Bill Smith",
#"position" : #"tester"
},
#{
#"id": #"4444",
#"name" : #"Bill Smith",
#"position" : #"tester"
}];
You can use NSJSONSerialization to take an NSData with your JSON, and parse it into a native Foundation object.
In this case, if you receive the NSData from the JSON snippet you pasted, you'd have an NSArray returned which contains 2 NSDictionary objects. Here is how you can accomplish that using NSJSONSerialization:
[NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableLeaves error:&error];
Note that the documentation says:
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
So do ensure that you receive the data in one of those encoded formats. This is the quickest way to do it, it's built in to Cocoa and is very, very fast. Also, you can have different options than NSJSONReadingMutableLeaves.
Hope this helps :)
oh well. I have not found any clever solution to this so I simply took a substring from the entire response object to extract all content between first and last {} or first and last []. Works just as well.
I'm quite new to programming and I been googling but couldn't find exactly what I'm looking for.
ok I send a request by ajax and I get response similar to this (the original json is much more complicated)
{
"shelf": {
"genre": {
"title1": {
"date": "date",
"author": "name",
"featured": "N"
}
"title2": {
"date": "date",
"author": "name",
"featured": "Y"
}}}
now I need to do find a "book" which is featured. So I have been looking for a way to look for featured = Y and get it's title in this case "title2".
The best way I could figure out is that when I create the json (in php) when something is featured I can create a new key => value at the same level as "shelf"
"shelf": {
"genre": {
"title1": {
/.../
}
"title2": {
/.../
}}}
"featured": {
"genre": "featuredTitle"
"genre2":"featuredTitle2"
}}}
and then access it in javascript like this:
response.featured['genre'];
and then get all the data by going to
response.shelf.genre.title
but there must be a better way to do it... this gets very messy when the json is very complicated.
Thanks,
Tom
Almost there. You can loop through a JSON object quite easily, JSON is a very friendly format.
var genres = response.shelf.genre;
for (title in genres) {
if (genres.hasOwnProperty(item)) {
var bookTitle = title;
var featured = genres[title].featured;
}
}
The hasOwnProperty is a safety feature you should always use when looping through a JSON object. You can find out more about it here.
More on JSON
JSON solely consists of Javascript Objects and Arrays, one or the other. So even if the stack is complicated, you can always parse it by traversing either an object or an array, and so long as you know the structure of the JSON, it is easy to parse.
// Objects:
myJSON.subObject.anotherSubobject.andAnotherOne;
// Arrays:
myJSON[0]; // accesses first item in array...
myJSON.subObject[2]; // accesses third item in the subObject array.
I have a json output that looks like this.
{
"38467": {
"name": "Tony Parker",
"book": [
{
"title": {
"name": "MediaWorks"
},
},
],
}
"59678": {
"name": "Ray Thomas",
}
}
Actually json output is a lot bigger list. But I want to only save author's name and their publisher. I want save multiple individual records for a single model.
I am using jquery to assign input elements their values.
$('#Author' + i + 'Title').val(response...);
But it is not working.
I appreciate any help.
Thanks.
JSON is just javascript data - a javascript object. Assign the "decoded" JSON data to a variable (say var dat), then you can access members the normal object/array away: dat[38467]['name'] is Tony Parker and so on.
comment update:
once you've decoded/stored the data, you can use a regular javascript foreach loop to go over it:
for (var bookID in booklist) {
var author = booklist[bookID]['name'];
var title = booklist[bookID]['book'][0]['title']['name'];
// ...do stuff here...
}
There's nothing magical about JSON, it's just javascript data packed up for easy/clean transmission. Of course, if you're using a framework such as jQuery or MooTools, you'd be better off using their own .each() operators, otherwise you'll get various bits of useless fluff from the for() loop.
edit: fixed code sample as per marimuthu's comment (good catch, thanks).