none
c# formatting json one line to indented without serialization RRS feed

  • Question

  • i have a json file that is all one line and not the way i want it. if i load in in *vs code* and do <kbd>Alt</kbd> <kbd>Shift</kbd> <kbd>F</kbd> it formats it lovely for me.

    This is code i currently have:



    {"ssrProps":{"header": {"enterpriseBlogBaseUrl": "https://sketchfab.com/blogs/enterprise", "isTransparent": false, "categories": [{"name": "Animals &amp; Pets", "uid": "ed9e048550b2478eb1ab2faaba192832", "slug": "animals-pets"}, {"name": "Architecture", "uid": "f825c721edb541dbbc8cd210123616c7",




    the file is so much longer than this is just a sniplet its all one line and if i load it into vs code and do shift alt f it turns it into this


    {
        "ssrProps": {
            "header": {
                "enterpriseBlogBaseUrl": "https://sketchfab.com/blogs/enterprise",
                "isTransparent": false,
                "categories": [
                    {
                        "name": "Animals &amp; Pets",
                        "uid": "ed9e048550b2478eb1ab2faaba192832",
                        "slug": "animals-pets"
                    },
                    {
                        "name": "Architecture",
                        "uid": "f825c721edb541dbbc8cd210123616c7",
                        "slug": "architecture"
                    },
                    {
                        "name": "Art &amp; Abstract",
                        "uid": "e56c5de1e9344241909de76c5886f551",
                        "slug": "art-abstract"
                    },
                    {
                        "name": "Cars &amp; vehicles",
                        "uid": "22a2f677efad4d7bbca5ad45f9b5868e",
                        "slug": "cars-vehicles"
                    },
                    {
                        "name": "Characters &amp; Creatures",
                        "uid": "2d643ff5ed03405b9c34ecdffff9d8d8",
                        "slug": "characters-creatures"
                    },
                    {
                        "name": "Cultural Heritage &amp; History",
                        "uid": "86f23935367b4a1f9647c8a20e03d716",
                        "slug": "cultural-heritage-history"
                    },
                    {
                        "name": "Electronics &amp; Gadgets",
                        "uid": "d7cebaeca8604ebab1480e413404b679",
                        "slug": "electronics-gadgets"
                    },
                    {
                        "name": "Fashion &amp; Style",
                        "uid": "81bfbbfa2c9b4f218eed8609e3cf7aa6",
                        "slug": "fashion-style"
                    },
                    {
                        "name": "Food &amp; Drink",
                        "uid": "b3631aefd82b4eeba37aa5fc0b73b05a",
                        "slug": "food-drink"
                    },
                    {
                        "name": "Furniture &amp; Home",
                        "uid": "606f202e5a3c4e62bf9aab1cd9f63e1b",
                        "slug": "furniture-home"
                    },
                    {
                        "name": "Music",
                        "uid": "357487fbb30a44ee8a0adf9b24829919",
                        "slug": "music"
                    },
                    {
                        "name": "Nature &amp; Plants",
                        "uid": "1a99e2b67fc84de0b3ea0d3925208a04",
                        "slug": "nature-plants"
                    },
                    {
                        "name": "News &amp; Politics",
                        "uid": "34edc263260f43e693ed527495b6d9a4",
                        "slug": "news-politics"
                    },
                    {
                        "name": "People",
                        "uid": "93e6d27da62149c6b963039835f45997",
                        "slug": "people"
                    },
                    {
                        "name": "Places &amp; Travel",
                        "uid": "c51b29706d4e4e93a82e5eea7cbe6f91",
                        "slug": "places-travel"
                    },
                    {
                        "name": "Science &amp; Technology",
                        "uid": "17d20ca7b35243d4a45171838b50704c",
                        "slug": "science-technology"
                    },
                    {
                        "name": "Sports &amp; Fitness",
                        "uid": "ac8a0065d9e34fca8a3ffa9c6db39bff",
                        "slug": "sports-fitness"
                    },
                    {
                        "name": "Weapons &amp; Military",
                        "uid": "3badf36bd9f549bdba295334d75e04d3",
                        "slug": "weapons-military"
                    }
                ],
                "communityBlogBaseUrl": "https://sketchfab.com/blogs/community"
            },
    ```
    but for the life of me i cant seem to get it to do this programicly witch is what i need to do 



    what i have tryied is all of the following

    private const string INDENT_STRING = "    ";
    
    static string FormatJson(string json) {
    
        int indentation = 0;
        int quoteCount = 0;
        var result = 
            from ch in json
            let quotes = ch == '"' ? quoteCount++ : quoteCount
            let lineBreak = ch == ',' && quotes % 2 == 0 ? ch + Environment.NewLine +  String.Concat(Enumerable.Repeat(INDENT_STRING, indentation)) : null
            let openChar = ch == '{' || ch == '[' ? ch + Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, ++indentation)) : ch.ToString()
            let closeChar = ch == '}' || ch == ']' ? Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, --indentation)) + ch : ch.ToString()
            select lineBreak == null    
                        ? openChar.Length > 1 
                            ? openChar 
                            : closeChar
                        : lineBreak;
    
        return String.Concat(result);
    }
    

    var x = JsonConvert.SerializeObject(jsonString, Formatting.Indented);


    i cant use serialization as its a external json file and the file is huge but for some reason visual code allows me to format it perfect with shift alt f formats it to the way i want to but i need to do it programmaticly because i have wrote code to work with the other formatted one and it looks so much neater like that 

    but none of this is working well and i cant seem to understand why vscode can do it but vs studio cant any help would be much appreciated.

    Monday, September 9, 2019 12:05 AM

Answers

  • Hi elfenliedtoprfan2,

    Thank you for posting here.

    You could try the following code to format json string.

    Before that, we need install Newtonsoft.Json nuget package.

    Code:

                string someJson = "{\"ErrorMessage\": \"\",\"ErrorDetails\": {\"ErrorID\": 111,\"Description\":{\"Short\": 0,\"Verbose\": 20},\"ErrorDate\": \"\"}}";
                Console.WriteLine(someJson);
                Console.WriteLine("*********************");
                JObject json = JObject.Parse(someJson);
                string a = json.ToString();
                Console.WriteLine(a);

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, September 9, 2019 2:23 AM
    Moderator

All replies

  • Hi elfenliedtoprfan2,

    Thank you for posting here.

    You could try the following code to format json string.

    Before that, we need install Newtonsoft.Json nuget package.

    Code:

                string someJson = "{\"ErrorMessage\": \"\",\"ErrorDetails\": {\"ErrorID\": 111,\"Description\":{\"Short\": 0,\"Verbose\": 20},\"ErrorDate\": \"\"}}";
                Console.WriteLine(someJson);
                Console.WriteLine("*********************");
                JObject json = JObject.Parse(someJson);
                string a = json.ToString();
                Console.WriteLine(a);

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, September 9, 2019 2:23 AM
    Moderator
  • thank you so much that worked perfectly :) 
    Monday, September 9, 2019 7:17 PM