views:

62

answers:

2

Is it at all possible to use variable names in JSON properties for JSON object ceration?

Example

CreateJSON("myProperty");

function CreateJSON (propertyName){
  var myObject = { propertyName : "Value"};

  document.write(myObject.popertyName);  // prints "value"
  document.write(myObject.myProperty);  // Does not exist
}
+3  A: 

If, in JavaScript, you want to use a variable for a property name, you have to create the object first, and then assign the property using square bracket notation.

var foo = "bar";
var ob  = {};
ob[foo] = "something"; // === ob.bar = "something"

If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the stringify method of the JavaScript JSON library on json.org

David Dorward
A: 

You can sort of do this:

  var myObject = {};
  CreateProp("myProperty","MyValue");

  function CreateProp(propertyName, propertyValue)
  {
      myObject[propertyName] = propertyValue;
      alert(myObject[propertyName]);  // prints "MyValue" 
  };

I much perfer this syntax myself though:

function jsonObject()
{
};
var myNoteObject = new jsonObject();

function SaveJsonObject()
{
    myNoteObject.Control = new jsonObject();
    myNoteObject.Control.Field1= "Fred";
    myNoteObject.Control.Field2= "Wilma";
    myNoteObject.Control.Field3= "Flintstone";
    myNoteObject.Control.Id= "1234";
    myNoteObject.Other= new jsonObject();
    myNoteObject.Other.One="myone";
};

Then you can use the following:

SaveJsonObject();
var myNoteJSON = JSON.stringify(myNoteObject);

NOTE: This makes use of the json2.js from here:http://www.json.org/js.html

Mark Schultheiss