views:

28

answers:

1

Using Facebook Search API, I got an response like:

"data" : [
    {
        "created_time" : "2010-07-24T19:47:31+0000",
        "description" : "...",
        "icon" : "...",
        "id" : "1",
        "link" : "...",
        "name" : "...",
        "type" : "link",
        "updated_time" : "2010-07-24T19:47:31+0000" 
    },
    {
        "created_time" : "2010-07-24T14:57:51+0000",
        "id" : "2",
        "message" : "...",
        "type" : "status",
        "updated_time" : "2010-07-24T14:57:51+0000" 
    },

BTW, first variable isn't always "created_time". I need to change that type attribute position due a DataContractJsonSerializer requirement for polymorphism:

Type Hint Position in JSON Objects Note that the type hint must appear first in the JSON representation. This is the only case where order of key/value pairs is important in JSON processing.

Result must be:

"data" : [
    {
        "__type" : "link:#Facebook",
        "created_time" : "2010-07-24T19:47:31+0000",
        "description" : "...",
        "icon" : "...",
        "id" : "1",
        "link" : "...",
        "name" : "...",
        "updated_time" : "2010-07-24T19:47:31+0000" 
    },
    {
        "__type" : "status:#Facebook",
        "created_time" : "2010-07-24T14:57:51+0000",
        "id" : "2",
        "message" : "...",
        "updated_time" : "2010-07-24T14:57:51+0000" 
    },
A: 

For me, the following works:

Search for

\{(\s+)([^}]*?)"type" : "([^"]*)",\s+

and replace with

{\1"__type" : "\3:#facebook"\1\2

This looks for an opening brace, grabs everything until the first type entry (failing the match if the block doesn't contain one), stores its value and replaces it at the beginning of the block's contents.

Nested blocks aren't supported (don't know if they might occur).

In C#:

resultString = Regex.Replace(subjectString, @"\{(\s+)([^}]*?)""type"" : ""([^""]*)"",\s+", "{$1\"__type\" : \"$3:#facebook\"$1$2");
Tim Pietzcker
For more complex scenarios, this doesn't works. I gave up on this approach, but thanks for your time!
Rubens Farias