Edit the processed JSON

I have a JSON file contact.txt

that has been parsed into a named object 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 foresaw editing the file / object, taking data from the form to add more contacts. How can i do this?

The following way to add a new contact to the array JSONObj

doesn't seem to work, 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);

      

+2


source to share


2 answers


It depends on what technology you are using. The main process is to read the file, convert it to any native data types (hash, dict, list, etc.) using the JSON parsing library, modify or add the data to your own object, and then convert it back to JSON and save it to a file.

In Python, using the simplejson library , it looks like this:

import simplejson

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

#python 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 could be retrieved from another file or web application request / form data, etc. If you are doing this in a web application though I would advise not to read and write the same file (in case of entering two requests at the same time).



Please provide additional information if this does not answer your question.


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

To parse a JSON string to Javascript, you can either use eval

it (unsafe) or use a JSON parser like this one JSON.parse

. Once you have your converted JSON object, you can make any changes you want in standard JS. Then you can use this same library to convert JS object to JSON string ( JSON.stringify

). Javascript does not allow access to files (unless you are running serveride JS ), so this will prevent you from reading and writing to the contact.txt

file directly. You will have to use a server-side language (like Python, Java, etc.) to read and write the file.

+1


source


Once you read into JSON, you just have an associative array, or rather, you have a pseudo-associative array, since this is Javascript. Anyway, you can think of this thing as one big list of dictionaries. You can access it using 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 every 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, read it into memory, edit the list of dictionaries, and write it back to the file.

Your JSON library will have a function to turn JSON into a string, just as it turns a string into JSON.

ps I suggest you follow JavaScript rules and use camel for variable names unless you have any other custom in your place of work. http://javascript.crockford.com/code.html

0


source







All Articles