How to minify json response? - javascript

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.

Related

How to parse JSON with number as a key

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

How to parse out a JSON array from Javascript assignment using regex in iOS?

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.

json - look for value and key

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.

Generating Tree Structure from Flat Array in JavaScript (without using object references)

I'm trying to generate a tree structure in JavaScript from a flat array. This would usually be a fairly straightforward proposition - simply retain a 'stack' array with references to ancestor objects of the current working scope ordered by nesting depth - push a new element onto the stack when entering another nested level, and pop it off when leaving one, replacing the current working element with the object referenced by the (new) last array item.
Unfortunately this requires the capability to pass-by-reference, which JavaScript doesn't have (well, doesn't have in any meaningful way that I know how I could use for this problem.)
To give a bit of background, I'm trying to turn an arbitrarily long/complicated string containing nested XML-style (but not XML, so an XML parser can't be used instead) tokens into a structure similar to the one below:
Expected Input:
[
"<token>",
"<my non compliant token>",
"some text at this level",
"<some other token>",
"some more text",
"<yet another token>",
"more text",
"</yet another token>",
"blah!",
"</some other token>",
"</token>",
"more text"
]
Expected Output
[
{
"token": "<token>",
"children": [
{
"token": "<my non compliant token>",
"children": [
"some text at this level",
{
"token": "<some other token>",
"children": [
"some more text",
{
"token": "<yet another token>",
"children": [ "more text" ]
},
"blah!"
]
}
]
}
]
},
"more text"
]
To clarify - I'm not after an entire algorithm (but I'd be interested if you want to provide your implementation) - just a good method for maintaining current position in the outputted tree (or an entirely different/better way of generating tree objects!) Don't get too caught up on how the tokens work - they're not XML and for the purpose of the exercise could be formatted entirely differently.
Any input would be greatly appreciated!
Your strings look easy to parse. I think I would do something like this:
var stack = [];
var array = [];
for (var i in strings) {
var s = strings[i];
if (s.indexOf("</") == 0) {
array = stack.pop();
} else if (s.indexOf("<") == 0) {
var obj = {token: s, children: []};
array.push(obj);
stack.push(array);
array = obj.children;
} else {
array.push(s);
}
}
Idea #1
Here's an answer you probably weren't anticipating.
Looking at your expect output, I was wondering if it's easiest to just generate JSON and then eval it when you're done. No references at all.
When going through your flat array, you basically have three operations:
You add more data to the current object
You close off the current object
You create a new child object
You can do all three of those fairly easily by just appending the appropriate text onto a JSON string you're building as you iterate through your source array to literally just generate the text you show in your expected output. When done, run that JSON string through eval. You may need a few safety checks to verify that each array and object is closed properly if there are errors in the input, but it should work fine.
Idea #2
You can still use your stack array. I'm not sure exactly why you need to pass by reference, but you can just pass an index into the array around and have everyone modify the master copy of the array that way via index. Using local functions, the master array can be a common data value that is local to your main function, but essentially global to all your sub-functions so they can all shared access to it.
This would look something like this:
function ParseRawData(rawData)
{
var parentScopeArray = []; // main parent scope of objects
function processTag(x)
{
// you can access parentScopeArray directly here and
// and be accessing it by reference
}
// other code or local functions here
}
Idea #3
If you want to pass the array into a function and have the master copy modified (perhaps the reason you're thinking of pass by reference), the javascript design pattern is to pass the array in and return a modified array, replacing the entire original array with the modified one that is returned.

How to retrieve data from json output

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

Categories

Resources