开发者

Regex to change attribute order in a JSON string?

开发者 https://www.devze.com 2023-01-09 09:26 出处:网络
Using Facebook Search API, I got an response like: \"data\" : [ { \"created_time\" : \"2010-07-24T19:47:31+0000\",

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 开发者_Go百科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" 
    },


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消