Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all articles
Browse latest Browse all 3333

Use PowerShell to Convert to or from JSON

$
0
0

Summary: Windows PowerShell MVP, Doug Finke, discusses using a simple Windows PowerShell command to convert to or from JSON.

Microsoft Scripting Guy, Ed Wilson, is here. Today we have guest blogger, Doug Finke.

Photo of Doug Finke

Microsoft Windows PowerShell MVP, Doug Finke is the author of Windows PowerShell for Developers. He works in New York City for Lab49, a company that builds advanced applications for the financial service industry. Doug is a developer, author, and speaker working with numerous technologies.

Blog: Hi, I'm Doug Finke!

JavaScript Object Notation (JSON) is a lightweight, text-based, open-standard that is designed for data interchange. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages, including Windows PowerShell.

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and a web application, serving as an alternative to XML.

The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, has a number field for age, contains an object representing the person’s address, and contains a list (an array) of phone number objects.

$json = @"

{

    "firstName": "John",

    "lastName" : "Smith",

    "age"      : 25,     "address"  :

    {

        "streetAddress": "21 2nd Street",

        "city"         : "New York",

        "state"        : "NY",

        "postalCode"   : "10021"

     },      "phoneNumber":

     [

         {

            "type"  : "home",

            "number": "212 555-1234"

         },

         {

            "type"  : "fax",

            "number": "646 555-4567"

         }

     ]

 }

"@

Converting JSON to Windows PowerShell objects and back

There’s a one-liner to take a string of JSON and convert it to a Windows PowerShell representation. The variable $PowerShellRepresentation contains the object, complete with properties and nested structures:

PS C:\> $PowerShellRepresentation = $json | ConvertFrom-Json

Now, let’s access the string that we converted in Windows PowerShell.

PS C:\> $PowerShellRepresentation

 

firstName   : John

lastName    : Smith

age         : 25

address     : @{streetAddress=21 2nd Street; city=New York; state=NY; postalCode=10021}

phoneNumber : {@{type=home; number=212 555-1234}, @{type=fax; number=646 555-4567}}

Windows PowerShell can interoperate with JSON. Being able to consume text and turn it into objects with properties makes it super-easy to get at information and consume it in the way you need to.

This isn’t a one-way ticket, though; we can take the round-trip. We’ll take the JSON we converted to Windows PowerShell and pipe it to ConvertTo-Json, and it will produce the JSON string we started with originally.

$PowerShellRepresentation | ConvertTo-Json

{

    "firstName":  "John",

    "lastName":  "Smith",

    "age":  25,

    "address":  {

                    "streetAddress":  "21 2nd Street",

                    "city":  "New York",

                    "state":  "NY",

                    "postalCode":  "10021"

                },

    "phoneNumber":  [

                        {

                            "type":  "home",

                            "number":  "212 555-1234"

                        },

                        {

                            "type":  "fax",

                            "number":  "646 555-4567"

                        }

                    ]

}

This means that we can work in Windows PowerShell, including creating directory listings (Windows PowerShell objects), reading XML (Windows PowerShell objects), calling methods on .NET DLLs, getting results (Windows PowerShell objects). Then we can pipe the results to ConvertTo-Json, and we’re ready to interact with services that accept JSON.

What if a web or REST service returns JSON?

If JSON is returned by a web or REpresentational State Transfer (REST) service, no problem. Windows PowerShell has a cmdlet that makes it incredibly easy to handle the request and conversion in a couple of lines of script:

$url = 'http://search.twitter.com/search.json?q=powershell'

(Invoke-RestMethod $url).results

Or even less if we use an alias:

(irm $url).results

Here is the first element of the array that returned from the Twitter search we just ran. Remember, each is accessible via the property name. Plus, because we are working with Windows PowerShell, we can leverage other cmdlets in Windows PowerShell, like Export-Csv, and then pipe the results to a comma-separated value file. This preps it for use in Excel, for example. That’s a great return on a single line of code.

created_at              : Sat, 24 Mar 2012 16:54:47 +0000

from_user               : denisemc06 from_user_id            : 78444415 from_user_id_str        : 78444415 from_user_name          : Denise McInerney geo                     : id                      : 183597742919135233 id_str                  : 183597742919135233

iso_language_code       : en

metadata                : @{result_type=recent}

profile_image_url       : http://a0.twimg.com/profile_images/1637362430/

headshot3_small_normal.jpg

profile_image_url_https : https://si0.twimg.com/profile_images/1637362430/

headshot3_small_normal.jpg

source                  : <a href="http://www.tweetdeck.com"

rel="nofollow">TweetDeck</a>

text                    : Getting #powershell schooling from @SQLvariant at #sqlsat120 to_user                 : to_user_id              : to_user_id_str          : to_user_name            :

So, we can now consume and produce JSON, the Internet lingua franca. We can query REST services and let Windows PowerShell automatically convert JSON to Windows PowerShell objects, which can be piped to other Windows PowerShell functions or cmdlets and transformed to different shapes and formats. Anytime I find myself reaching for cUrl or wget, I first check to see if I can do what I need in Windows PowerShell 3.0.

~Doug

About Doug’s book

Here is a bit about Doug Finke’s book Windows PowerShell for Developers. “For Developers” is in the title, but if you are an IT Pro, this book gives you deeper insight into Windows PowerShell and ways it can be used.

  • Slice and dice text, XML, CSV, and JSON with ease

  • Embed Windows PowerShell to provide scripting capabilities for your C# apps

  • Create GUI applications five to ten times faster with less code

  • Leverage Windows PowerShell’s capabilities to work with the Internet

  • Interact with DLLs and create objects, automatically display properties, and call methods in live interactive sessions

  • Build domain-specific languages (DSLs) and vocabularies to express solutions more clearly

  • Work with Microsoft Office via the Component Object Model (COM)

  • Discover Windows PowerShell 3.0 features that are included in Windows 8 and Windows Server 2012

Image of book cover

Windows PowerShell for Developers, First Edition
by Douglas Finke
ISBN-10: 1449322700
ISBN-13: 978-1449322700
http://shop.oreilly.com/product/0636920024491.do
Copyright 2012 Douglas Finke. All rights reserved. Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

Thanks for sharing this information from your book, Doug.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


Viewing all articles
Browse latest Browse all 3333

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>