views:

93

answers:

1
Q: 

RegEx Help

I'm using JSON for a web application I'm developing. But for various reasons I need to create "objects" that are already defined on the client script based on the JSON response of a service call. For this I would like to use a regex expression in order to insert the "new" statements into the JSON response.

function Customer(cust)
{
    this.Name = null;
    this.ReferencedBy = null;
    this.Address = null;

    if (cust != null)
    {
        this.Name = cust.Name;
        this.ReferencedBy = cust.ReferencedBy;
        this.Address = cust.Address;
    }
}

The JSON response is returned by an ASP.NET AJAX Service and it contains a "__type" member that could be used to determine the object type and insert the "new" statement.

Sample JSON:

{"__type":"Customer", "ReferencedBy":{"__type":"Customer", "Name":"Rita"}, "Name":"Joseph", "Address":"123 {drive}"}

The resulting string would look like this:

new Customer({"ReferencedBy":new Customer({"Name":"Rita"}), "Name":Joseph", "Address":"123 {drive}"})

I got this so far but it doesn't work right with the ReferencedBy member.

match:

({"__type":"Customer",)(.*?})

replace:

new Customer({$2})

Thanks for your help.

+1  A: 

Hmmm why don't you try to make a simplier way to do it? e.g.:

var myJSON =     {"__type":"Customer", "ReferencedBy":{"__type":"Customer", "Name":"Rita"}, "Name":"Joseph", "Address":"123 {drive}"};

after check the type: myJSON.__type, and if it is customer, then:

new Customer({"ReferencedBy":new Customer({"Name":myJSON.ReferencedBy.Name}), "Name":myJSON.Name, "Address":myJSON.Address });

It is because you already have a defined data structure, it is not neccessary to use regex to match pattern & extract data.

Murvinlai
Thanks for the answer but that won't solve the problem with the ReferencedBy member.The sample I posted is just a small test case, there are hundreds of different types in the application and the response JSON could be a very complex web of objects, so I do need to transform the string.
Joe Bloggs