X

NV5 Geospatial Blog

Each month, NV5 Geospatial posts new blog content across a variety of categories. Browse our latest posts below to learn about important geospatial information or use the search bar to find a specific topic or author. Stay informed of the latest blog posts, events, and technologies by joining our email list!



From Image to Insight: How GEOINT Automation Is Changing the Speed of Decision-Making

From Image to Insight: How GEOINT Automation Is Changing the Speed of Decision-Making

4/28/2025

When every second counts, the ability to process geospatial data rapidly and accurately isn’t just helpful, it’s critical. Geospatial Intelligence (GEOINT) has always played a pivotal role in defense, security, and disaster response. But in high-tempo operations, traditional workflows are no longer fast enough. Analysts are... Read More >

Thermal Infrared Echoes: Illuminating the Last Gasp of a Dying Star

Thermal Infrared Echoes: Illuminating the Last Gasp of a Dying Star

4/24/2025

This blog was written by Eli Dwek, Emeritus, NASA Goddard Space Flight Center, Greenbelt, MD and Research Fellow, Center for Astrophysics, Harvard & Smithsonian, Cambridge, MA. It is the fifth blog in a series showcasing our IDL® Fellows program which supports passionate retired IDL users who may need support to continue their work... Read More >

A New Era of Hyperspectral Imaging with ENVI® and Wyvern’s Open Data Program

A New Era of Hyperspectral Imaging with ENVI® and Wyvern’s Open Data Program

2/25/2025

This blog was written in collaboration with Adam O’Connor from Wyvern.   As hyperspectral imaging (HSI) continues to grow in importance, access to high-quality satellite data is key to unlocking new insights in environmental monitoring, agriculture, forestry, mining, security, energy infrastructure management, and more.... Read More >

Ensure Mission Success With the Deployable Tactical Analytics Kit (DTAK)

Ensure Mission Success With the Deployable Tactical Analytics Kit (DTAK)

2/11/2025

In today’s fast-evolving world, operational success hinges on real-time geospatial intelligence and data-driven decisions. Whether it’s responding to natural disasters, securing borders, or executing military operations, having the right tools to integrate and analyze data can mean the difference between success and failure.... Read More >

How the COVID-19 Lockdown Improved Air Quality in Ecuador: A Deep Dive Using Satellite Data and ENVI® Software

How the COVID-19 Lockdown Improved Air Quality in Ecuador: A Deep Dive Using Satellite Data and ENVI® Software

1/21/2025

The COVID-19 pandemic drastically altered daily life, leading to unexpected environmental changes, particularly in air quality. Ecuador, like many other countries, experienced significant shifts in pollutant concentrations due to lockdown measures. In collaboration with Geospace Solutions and Universidad de las Fuerzas Armadas ESPE,... Read More >

1345678910Last
«May 2025»
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
16110 Rate this article:
1.5

Using JSON and XML to save and restore parameters

Anonym

When writing IDL code, it is often convenient to be able to save and restore parameters used in the code. This could be algorithm constants or thresholds used to perform computations, or it might be the status of the checkboxes on a user interface. In earlier versions of IDL, a static structure was often used to store such information. In IDL 8.3, the ordered hash is probably the best choice for this purpose.

The ordered hash object is dynamic, and can be nested. Here is an example:

IDL> param = OrderedHash()

IDL> param['sigma'] = !dpi/4

IDL> param['xsize'] = 512

IDL> param['name'] = 'Exelis'

IDL> param

{

   "sigma": 0.78539816339744828,

   "xsize": 512,

   "name": "Exelis"

}

And with nesting:

IDL> tmp = OrderedHash('alpha', 1, 'beta', [255,240,190])

IDL> param['subparam'] = tmp

IDL> param

{

   "sigma": 0.78539816339744828,

   "xsize": 512,

   "name": "Exelis",

   "subparam": {

       "alpha": 1,

       "beta": [255, 240, 190]

   }

}

 

The simplest way to save such data is to use IDL's SAVE procedure.  However, the resulting file will be in a binary format that is not accessible unless you use IDL's RESTORE procedure. If you want the configuration parameters to be editable in a text editor or accessible to another programming language, it is better to use a readable format such as JSON or XML. Here is an example using JSON:

 

IDL> json = JSON_SERIALIZE(param)

IDL> json

{"sigma":0.785398163397448,"xsize":512,"name":"Exelis","subparam":{"alpha":1,"beta":[255,240,190]}}

 

In this example "json" is a string representation of the OrderedHash object.

 

 

To restore the parameters at a later time, use:

 

IDL> newparam = JSON_PARSE(string(read_binary(filename)))

 

This will create a new ordered hash from the string that was read from a file in this case. The JSON format has a limited set of built-in types that it supports, so, IDL variables will not necessarily retain the exact same type after going through JSON_SERIALIZE and JSON_PARSE. For example, in this case, the array was converted into a list, since JSON arrays correspond more closely to IDL's list than an IDL array. Numbers are always returned as double precision floating point or long64 integers.

 

Finally, I am including a simple example of adding XML serialization and de-serialization to the ordered hash. Since OrderedHash inherits from Hash, the methods are added to Hash. The first method is hash__toxml.pro

function hash::ToXml,_ref_extra=extra

 compile_opt idl2,logical_predicate

 nl = string(10b)

 formats = hash(4,'(g0.9)',5,'(g0.17)',6,'("(",g0.9,",",g0.9,")")',9,'("(",g0.17,",",g0.17,")")')

 oXml = IDLffXmlDomDocument()

 oTop = oXml.CreateElement('TOP')

 parent = oXml.AppendChild(oTop)

 keys = self->Keys()

 foreach k, keys do begin

   val = self[k]

   type = size(val, /type)

   node = oXml.CreateElement(k)

   node.SetAttribute, 'TYPE', strtrim(type, 2)

   if isa(val, /array) then node.SetAttribute,'ARRAY', $

     strjoin(string(size(val, /dimension),format='(i0)'), ' ')

   format = formats.HasKey(type) ? formats[type] : '(i0)'

   str = (type eq 7)?strjoin(val, nl):strjoin(string(val, format=format), ' ')

   txt = oXml.CreateTextNode(str)

   _ = node.AppendChild(txt)

   _ = parent.AppendChild(oXml.CreateTextNode(nl))

   _ = parent.AppendChild(node)

 endforeach

 _ = parent.AppendChild(oXml.CreateTextNode(nl))

 if n_elements(extra) then oXml.Save, _strict_extra=extra

 return, oXml

end

With this method an ordered hash can be turned into XML using the following code:

IDL> param = OrderedHash()

IDL> param['sigma'] = !dpi/4

IDL> param['xsize'] = 512

IDL> param['name'] = 'Exelis'

IDL> param['theta'] = [[23, 334, 4.0, 41.0], [1.0, 2, 3, 4]]

IDL> !null = param.ToXml(string=str)

% Loaded DLM: XML.

% Compiled module: HASH::TOXML.

IDL> str

<?xml version="1.0"encoding="UTF-8" standalone="no" ?><TOP>

<sigmaTYPE="5">0.78539816339744828</sigma>

<xsizeTYPE="2">512</xsize>

<nameTYPE="7">Exelis</name>

<theta ARRAY="4 2"TYPE="4">23 334 4 41 1 2 3 4</theta>

</TOP>

Then, to turn the resulting string back into an OrderedHash, use:

pro hash::FromXml_,_ref_extra=extra

 compile_opt idl2,logical_predicate, static

 oXml = IDLffXmlDomDocument()

 oXml.Load, _strict_extra=extra

 top = oXml.GetDocumentElement()

 nodes = top.GetChildNodes()

 for i=0, nodes.GetLength()-1 do begin

   n = nodes.Item(i)

   if isa(n, 'IDLffXmlDomElement') then begin

     array = []

     key = n.GetTagName()

     txt = n.GetFirstChild()

     if isa(txt, 'IDLffXmlDomText') then str = txt.GetData()

     type = n.GetAttribute('TYPE')

     array = n.GetAttribute('ARRAY')

     if type eq 7 && ~keyword_set(array) then val = str $

     else if type eq 7 then begin

       val = reform(strsplit(str, string(10b), /extract), $

          long64(strsplit(array, /extract)))

     endif else begin

       if keyword_set(array) then begin

          val = make_array(long64(strsplit(array, /extract)),type=type)

       endif else val = (make_array(1, type=type))[0]

       reads, str, val

     endelse

     self[key] = val

   endif

 endfor

end

Using a static method helps the syntax:

function OrderedHash::FromXML,_ref_extra=extra

 compile_opt static

 objref = OrderedHash()

 objref.FromXML_, _strict_extra=extra

 return, objref

end

Here is an example converting the string variable "str" back into an OrderedHash:

IDL> newparam = OrderedHash.FromXML(string=str)

IDL> newparam

{

   "sigma": 0.78539816339744828,

   "xsize": 512,

   "name": "Exelis",

   "theta": [[23.000000, 334.00000, 4.0000000, 41.000000],[1.0000000, 2.0000000, 3.0000000, 4.0000000]]

}

This small example does not support nested hash objects, lists, and has a problem with string arrays containing newline characters.

Please login or register to post comments.