JSON.stringify() won’t output Object properties if your variable is an Array

by zack.moore June 25, 2010 23:39

I was recently editing some code that another developer had written when I noticed some strange behavior.

Note: in this post I use the terms “object properties”, “expando properties”, and “dictionary values” interchangeably. In JavaScript, you can add named values to an object in a few ways but each is mostly interchangeable. For example, these do the same thing:

x["a"] = 1;
x.a = 1;

I needed to take an existing JavaScript object and stringify it and send the JSON to the server. That’s fairly straightforward, but

Technorati Tags:

I quickly realized that the JSON I was receiving was missing a bunch of values that I was expecting.

It turned out the source of the error was in the variable declaration of the object I was stringifying. The variable was declared as:

var a = new Array();

But, when values were added to the variable they were added using the dictionary syntax such as:

a[“key”] = 3;

Even though the variable is declared wrong, it appeared to work fine everywhere. That is, until I tried to stringify it.

A quick note, if you don’t know what stringify is then take a look over at json.org. The short answer is that stringify() is a method on the JSON object that lets you turn a JavaScript object into its JSON representation.

The problem seems to be that when stringify() encounters an array object, while it does serialize the indexed elements it doesn’t serialize any expando properties.

This makes sense if you think about it. JSON has a representation for objects with properties and for arrays, but the array notation has no way of also including properties.

The example below demonstrates that no dictionary values that were added to the array are serialized when the array is stringified, but in the object the properties are output. Note, I used the shorthand notation for object {} and array [] in the example below.

Example Code:

<label for="out_a1">A property read: </label><span id="out_a1"></span><br />
<label for="out_a2">A strinify: </label><span id="out_a2"></span><br />
<label for="out_b1">B property read: </label><span id="out_b1"></span><br />
<label for="out_b2">B strinify: </label><span id="out_b2"></span><br />
<script type="text/javascript">
    var a = {};
    var b = [];

    a["alpha"] = "alpha";

    b["beta"] = "beta";

    var out_a1 = document.getElementById("out_a1");
    out_a1.innerHTML = a["alpha"];
    var out_a2 = document.getElementById("out_a2");
    out_a2.innerHTML = JSON.stringify(a);

    var out_b1 = document.getElementById("out_b1");
    out_b1.innerHTML = b["beta"];
    var out_b2 = document.getElementById("out_b2");
    out_b2.innerHTML = JSON.stringify(b);
</script>

 

Example Output:

A property read: alpha
A strinify: {"alpha":"alpha"}
B property read: beta
B strinify: []

The solution in my problem was to change the object declaration from array to object and everything worked fine.

I could have run into a problem if the object was being accessed as both an array and an object. You can do this. I tried it out in a couple of browsers (IE8 and Chrome) and it worked. If that had been the case, then I would have had to refactor the code because there would be not way to output both the array elements and the object properties in one JSON element.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

JavaScript

Google Pac-Man is 2 player with Ms. Pac-Man

by zack.moore May 28, 2010 13:35

Maybe everyone else already knew this, but I just figured it out.

As you probably know, Google recently replaced the normal Google logo on the search page with a playable Pac-Man game where the game map spelled out the word Google.

Not everyone knows that you can still get to the game by going to http://www.google.com/pacman/ or you can even download the code by going to http://github.com/macek/google_pacman

I’ve used this as a diversion ever since it came out and every time I played the same way. When the page comes up and finishes its startup sequence, I use the arrow keys to direct Pac-Man around the map gobbling up dots. When I finally run out of lives, I would hit the Insert Coin button and play some more.

Today I just randomly hit the Insert Coin button before I started playing and low and behold Ms. Pac-Man appeared on the screen beside Pac-Man.

A second person can play the Ms.Pac-Man at the same time that you play Pac-Man. Pac-Man is controlled by the arrow keys and Ms.Pac-Man is controlled by the W, A, S, and D keys: W is Up, A is Left, S is Down, and D is Right.

I used to play Pac-Man on our ATARI when I was growing up and I don’t remember how or if 2 play worked, but this is fun.

Enjoy!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

jQuery 1.4 Released

by zack.moore January 21, 2010 16:06

jQuery 1.4 was released on Thursday, 14 Jan 2010. I didn’t see this until today.

Head over to 14 Days of jQuery or the  jQuery home.

Looks like there have been some major performance improvements and some new features.

One that jumped out at me is that jQuery now takes advantage of the native JSON object if present when calling jQuery Ajax methods.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

SQL Server Temporary Stored Procedures

by zack.moore January 21, 2010 14:56

I learned something new today. In SQL Server you can create temporary stored procedures that automatically go away when your session closes.

Here is a good article on Temporary Stored Procedures.

I already knew that you could create temporary tables, but I hadn't known that the same applied to stored procedures.

Temporary tables are created by starting the table name with a # sign.

Example:

create table #mytbl 
( 
    [Name] varchar(50), 
    [Age] int 
)

The same trick is used for stored procedures.

Example:

create procedure #addName 
( 
    @Name varchar(50),
    @Age int 
) 
begin 
    insert into #myTbl([Name], [Age]) values(@Name, @Age) 
end


This is really useful for scripts that you use for different tasks that contain repeated code that you hate duplicating but you don’t really want to permanently load into the database.

For example, say you have a script that runs on your build and deployment that fixes up any server logins that may have become broken from a rebuild or some other action. You might have a script that looks like the following.

declare @name varchar(100)
 
set @name = 'NT AUTHORITY\NETWORK SERVICE'
 
-- check to see if login exists
if exists(select name from master.sys.syslogins where name = @name)
begin
    -- if login exists, check to see if user exists on db
    if not exists(select name from sys.sysusers where name = @name)
    begin
        -- if user does not exist on db, then add it and add roles
        exec sp_grantdbaccess @name
        exec sp_addrolemember 'db_owner', @name
        print @name
    end
    else
    begin
        exec SP_CHANGE_USERS_LOGIN 'AUTO_FIX', @name, NULL, '*****'
    end
end
 
set @name = 'APPSVR\svnprojects'
 
-- check to see if login exists
if exists(select name from master.sys.syslogins where name = @name)
begin
    -- if login exists, check to see if user exists on db
    if not exists(select name from sys.sysusers where name = @name)
    begin
        -- if user does not exist on db, then add it and add roles
        exec sp_grantdbaccess @name
        exec sp_addrolemember 'db_owner', @name
        print @name
    end
    else
    begin
        exec SP_CHANGE_USERS_LOGIN 'AUTO_FIX', @name, NULL, '*****'
    end
end
 
set @name = 'APPSRV\agentmgr'
 
-- check to see if login exists
if exists(select name from master.sys.syslogins where name = @name)
begin
    -- if login exists, check to see if user exists on db
    if not exists(select name from sys.sysusers where name = @name)
    begin
        -- if user does not exist on db, then add it and add roles
        exec sp_grantdbaccess @name
        exec sp_addrolemember 'db_owner', @name
        print @name
    end
    else
    begin
        exec SP_CHANGE_USERS_LOGIN 'AUTO_FIX', @name, NULL, '*****'
    end
end

This contains lots of duplicate code which is more difficult to read is also error prone if you need to update the code that is performed for each user.

Now consider the updated code using a temp stored procedure.

create procedure #addLogin
(
    @name varchar(256),
    @role varchar(256),
    @password varchar(256)
)
as
begin
    -- check to see if login exists
    if exists(select name from master.sys.syslogins where name = @name)
    begin
        -- if login exists, check to see if user exists on db
        if not exists(select name from sys.sysusers where name = @name)
        begin
            -- if user does not exist on db, then add it and add roles
            exec sp_grantdbaccess @name
            exec sp_addrolemember @role, @name
            print @name + ' granted access'
        end
        else
        begin
            exec SP_CHANGE_USERS_LOGIN 'AUTO_FIX', @name, NULL, @password
            print @name + ' fixed.'
        end
    end
end
go
 
exec #addLogin @name = 'NT AUTHORITY\NETWORK SERVICE', @role='db_owner', @password='*****'
exec #addLogin @name = 'APPSVR\svnprojects', @role='db_owner', @password='*****'
exec #addLogin @name = 'APPSRV\agentmgr', @role='db_owner', @password='*****'
go

Much shorter and much easier to read. the #addLogin stored procedure will automatically be dropped when the session is closed so I don’t have to worry about polluting my database with utility procedures that don’t need to hang around.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

sql server | TSQL

TrueCrypt 6.3 released. Now supports Win7 and Snow Leopard

by zack.moore October 23, 2009 11:36

TrueCrypt 6.3 was released on the a couple of days ago on 21 Oct 2009 and now has full Windows 7 (32 and 64bit) and Mac Snow Leopard support.

Some people had gotten the previous version, 6.2a to work with Windows 7 but others had run into some problems.  This new release should come as great news for people wanting to protect the data on their newly repaved or purchased PCs.

Get TrueCrypt here.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Security | Windows7

IronPython in Action

by zack.moore April 27, 2009 15:37

For a limited time, you can get IronPython in Action by Michael Foord and Christian Muirhead at 35% off. You can grab the discount code here at http://www.ironpythoninaction.com/ if it is still available.

IronPython is a .NET implementation of the Python programming language. It has been a long time since I looked at Python but I believe that its significant features are dynamic typing and dynamic binding.

IronPython is getting a lot of attention now and you can use it on ASP.NET, Windows, Console, and Silverlight projects. It is interesting because it offers different ways to solve problems and write algorithms, so for me I’m not looking at it as a C# replacement but as a supplement to my C# and other skills, but I’ll write a review up as I get into the book.

I got the eBook pretty cheap and I’m converting it for reading on my Kindle now.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

IE8 Released today

by zack.moore March 19, 2009 13:39

Head over to Microsoft and download the final version of IE8. You might have had a release candidate or beta version already but this is the final release version of version 8.

IE8 has a bunch of cool features which are better detailed at the IE web site than I could do, but suffice to say that I like it a lot and it runs pretty fast.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Lots of Cool announcements from MIX2009 – MVC, Silverlight, Expression, AJAX

by zack.moore March 19, 2009 13:27

At the MIX conference this week, Scot Gu announced the release version of ASP.NET MVC which has been widely anticipated.

You probably heard that already in the several hundred blogs and web pages that already announced it.

What you may not have read is that there is now documentation on MSDN for MVC. This is great for anyone who has been trying to learn MVC by following the increasingly out of date (but much appreciated) blog posts from since the early days of MVC.

Check out the MVC Documentation at MSDN.

You can get the latest MVC bits over at ASP.NET Downloads.

That brings up one of the other items announced at MIX, v2 of the Web Platform Installer. This is how I would recommend that you install the updated MVC bits and anything else from ASP.NET. Note though that you need to uninstall any beta or RC first before you launch the Web Platform Installer.

The Web Platform Installer has a bunch of other web and ASP.NET bits including the ability to install apps like BlogEngine.NET and even some PHP apps that run on Windows like Drupal. And since it runs off an RSS feed it will always have the most up to date listing.

Also announced at MIX is the Silverlight 3 Beta. You can get the beta and the Web Platform Installer will install the tools for Visual Studio. I haven’t installed it myself (yet) so I don’t know if the WPI will install all the Beta bits or just the VS Tools for Silverlight 3.

Here out this interview with Scot Gu on Silverlight 3 here.

One of the coolest things released are some of the new features in Expression Blend 3. You can get the current preview of Expression Blend 3 here but what you may get really exited about is the new SuperPreview feature which is a separate download (not sure if it is also included in the Blend 3 Preview). I haven’t installed Blend 3 yet but I haven installed the SuperPreview and it is very cool. Essentially what it allows you to do is see how your web pages look in  various browsers and versions of browses automatically without having to have those browsers installed AND it helps you find the tags and attributes and styles that are causing your pages to look different in each browser. The version that was demoed could show you your pages in IE8, IE7, IE6, Safari (version?), and FireFox (version?) which is very cool. Unfortunately the SuperPreview download can only compare your currently installed version of IE with IE6 but that is still very cool. I will be checking out the Blend Preview to see if it contains the full feature or the same as what is in the SuperPreview preview.

You can read more about SuperPreview here and read the Expression team’s blog entry and watch a SuperPreview video here.

You can read a summary of yesterday’s MIX keynotes here.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

LINQ and Code Generation Slides

by zack.moore January 14, 2009 12:26

On Monday I did a presentation with Chad Brooks and Dave Cameron at our local .NET User Group: MaconDotNet.

My sections were on LINQ and Code Generation. Other than me running a little long, the presentation went great. Here are my slides and examples but head over to the user group page to grab Chad and Dave's slides and examples when they get posted.

If you find any errors or typos, let me know.

(Note: I did a section on LINQ and a section on Code Generation. Not "LINQ and Code Generation")

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

sql server | Zack's Fiasco DAL | codegeneration | LINQ

ASP.NET eCommerce Solutions?

by zack.moore January 05, 2009 12:41

I had a long break after Christmas that I used to work on some projects. Sometimes it is hard to get any free time and it was a well enjoyed break.

I didn't get as much done on my XNA project as I would like but I've been studying the book pretty thoroughly.

My main project that I worked on was to build a web page for my dad's business. He has an old brink-and-mortar style business that was started by my grandfather. My dad is pretty tech savvy but he never got around to building a web page for his business so I thought it would be a good project.

I got a lot done on that and I'm talking to my sister and my wife to help me finish writing content for the site.

For my dad's web page I decided to investigate what it would take to add an eCommerce section and see if he was interested in selling a few items over the 'net as well as in person. So I started looking for a good ASP.NET based free eCommerce solution preferably that had built in support for PayPal's free (mostly) services. I figured there had to be lots of them out there but I didn't know one off the top of my head so I decided to look.

Turns out I was wrong, or at least I couldn't find as many as I thought. osCommerce seems to dominate the PHP world with several other strong competitors, but I didn't find as many stand-out ASP.NET kits.

However I did find 2 that seemed to be the best.

Microsoft used to have an eCommerce starter kit that you could download for ASP.NET. I don't know the details of how this happened but the kit has now been taken over by someone else and is called dashCommerce. The code is published under a free open source license and a commercial license with the main difference being a support agreement and the requirement that the free version must always display a message at the bottom of the page that reads "Powered by dashCommerce".

The other good product I found, which is also listed on Microsoft's ASP.NET web page, is DotShoppingCart. This product has as far as I can tell the same general options as dashCommerce, that you can use a free open source version as long as you leave the "Powered by DotShoppingCart" message at the bottom of every page or you can buy a commercial license with a support agreement.

I downloaded both products and tried them out using PayPal's sandbox. (btw, PayPal's sandbox is a pain to use.) I liked both. They are both similar in the features that they offer. They both have basic CMS tools and product catalogs. Both allow products to have configurable attributes like Size or Color or whatever you need. dashCommerce gives each product a different SKU per attribute while DotShoppingCart seems to give a product one SKU no matter the attributes. Both require SQL Server 2005 Express (or greater) with Advanced Services. I believe the main reason for this is that both use the Full Text searching. I don't know if either uses any of the other Advanced Features. Both have source code. dashCommerce uses SubSonic and log4net while DotShoppingCart uses the MS Enterprise Library. Both appear to have IPN support but I didn't test it.

I would also like to point out that ComponentOne also offers a free control library for dealing with PayPal. I haven't downloaded it or looked at it but it might be worth checking out and kudos to ComponentOne for offering it for free.

What do most people use? Either of the items I've listed or do you roll your own? Or is there another free or low cost kit or product that I have missed?

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

ASP.NET | eCommerce

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen | Modified by Mooglegiant


I've been doing software development since I was little and my dad first brough home an ATARI 800. I picked up PILOT and BASIC. Now I mostly write C# and ASP.NET, and about a dozen other languages and platforms. I also enjoy a bunch of outdoor sports including running and mountain biking. I am very happily married. I am currently working for a great Software and IT consulting company named SPINEN where I am a Senior Developer.


Copyright Zack Moore

TextBox