views:

314

answers:

2

I have a JSON file contact.txt that has been parsed into an object called JSONObj that is structured like this:

[
 {
   "firstName": "John",
   "lastName": "Smith",
   "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021"
   },
   "phoneNumbers": [
    { "type": "home", "number": "212 555-1234" },
    { "type": "fax", "number": "646 555-4567" }
   ]
  },

  {
   "firstName": "Mike",
   "lastName": "Jackson",
   "address": {
    "streetAddress": "21 Barnes Street",
    "city": "Abeokuta",
    "state": "Ogun",
    "postalCode": "10122"
   },
   "phoneNumbers": [
    { "type": "home", "number": "101 444-0123" },
    { "type": "fax", "number": "757 666-5678" }
   ]
  }
]

I envision editing the file/object by taking in data from a form so as to add more contacts. How can I do this?

The following method for adding a new contact to the JSONObj's array doesn't seem to be working, what's the problem?:

var newContact = {
    "firstName": "Jaseph",
    "lastName": "Lamb",
    "address": {
     "streetAddress": "25 2nd Street",
     "city": "New York",
     "state": "NY",
     "postalCode": "13021"
    },
    "phoneNumbers": [
     { "type": "home", "number": "312 545-1234" },
     { "type": "fax", "number": "626 554-4567" }
    ]
}
var z = contact.JSONObj.length;
contact.JSONObj.push(newContact);
A: 

Once you have read in the JSON, you just have an associative array - or rather you have a pseudo-associative array, since this is Javascript. Either way, you can treat the thing as one big list of dictionaries. You can access it by key and index.

So, to play with this object:

var firstPerson = JSONObj[0];
var secondPerson = JSONObj[1];

var name = firstPerson['firstName'] + ' ' + firstPerson['lastName'];

Since you will usually have more than two people, you probably just want to loop through each dictionary in your list and do something:

for(var person in jsonList) {

  alert(person['address']);

}

If you want to edit the JSON and save it back to a file, then read it into memory, edit the list of dictionaries, and rewrite back to the file.

Your JSON library will have a function for turning JSON into a string, just as it turns a string into JSON.

p.s. I suggest you observe JavaScript conventions and use camelcase for your variable names, unless you have some other customs at your place of employment. http://javascript.crockford.com/code.html

Andrew Johnson
+1  A: 

It depends on what technology you're using. The basic process is to read the file in, convert it to whatever native datatypes (hash, dict, list, etc.) using a JSON parsing library, modify or add data to the native object, then convert it back to JSON and store it to the file.

In Python, using the simplejson library it would look like this:

import simplejson

jsonobj = simplejson.loads(open('contact.txt'))

#python's dict syntax looks almost like JSON
jsonobj.append({
     'firstName': 'Steve',
     'lastName': 'K.',
     'address': {
          'streetAddress': '123 Testing',
          'city': 'Test',
          'state': 'MI',
          'postalCode': '12345'
     },
     'phoneNumbers': [
         { 'type': 'home', 'number': '248 555-1234' }
     ]
})

simplejson.dump(jsonobj, open('contact.txt', 'w'), indent=True)

The data in this example is hardcoded strings, but it could come from another file or a web application request / form data, etc. If you're doing this in a web app though I would advise against reading and writing to the same file (in case two requests come in at the same time).

Please provide more information if this doesn't answer your question.


In response to "isn't there way to do this using standard javascript?":

To parse a JSON string in Javascript you can either eval it (not safe) or use a JSON parser like this one's JSON.parse. Once you have the converted JSON object you can perform whatever modifications you want to it in standard JS. You can then use that same library to convert a JS object to a JSON string (JSON.stringify). Javascript does not allow file access (unless you're doing serverside JS), so that would prevent you from reading & writing to your contact.txt file directly. You'd have to use a serverside language (like Python, Java, etc.) to read and write the file.

lost-theory
This is exactly what I want to do, isn't there way to do this using standard javascript?
Tunji Gbadamosi
I'm basically trying to expand the object's array. Using push() doesn't seem to work, what will work?
Tunji Gbadamosi