Read json output with json.net (c#)

I have this json output.
var jsonstr = "{\"formattedResults\":{\"ruleResults\":{\"MinimizeRenderBlockingResources\":{\"localizedRuleName\":\"Eliminate render-blocking JavaScript and CSS in above-the-fold content\",\"ruleImpact\":12.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.\",\"args\":[{\"type\":\"INT_LITERAL\",\"key\":\"NUM_SCRIPTS\",\"value\":\"1\"},{\"type\":\"INT_LITERAL\",\"key\":\"NUM_CSS\",\"value\":\"3\"}]},\"urlBlocks\":[{\"header\":{\"format\":\"None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.\"}},{\"header\":{\"format\":\"{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/BlockingJS\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 1 output\"}]}}]},{\"header\":{\"format\":\"{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 2 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 3 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 4 output\"}]}}]}]},\"PrioritizeVisibleContent\":{\"localizedRuleName\":\"Prioritize visible content\",\"ruleImpact\":.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent\"}]}}}}}";
dynamic json = JsonConvert.DeserializeObject<dynamic>(jsonstr);
foreach (var item in json.formattedResults.ruleResults)
{
	Response.Write(item.Name+"<br>");
}

Open in new window

But I want this outpub. How does I crawl the json string to get the output? Does anybody know?
MinimizeRenderBlockingResources:
(Eliminate render-blocking JavaScript and CSS in above-the-fold content)
value 1 output
value 2 output
value 3 output
value 4 output

PrioritizeVisibleContent:
(Prioritize visible content)
Jesper ChristensenProgrammerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
sorry, what output you want to retrieve here?

as you got json below:

{
  "ruleResults": {
    "MinimizeRenderBlockingResources": {
      "localizedRuleName": "Eliminate render-blocking JavaScript and CSS in above-the-fold content",
      "ruleImpact": 12.0,
      "groups": [
        "SPEED"
      ],
      "summary": {
        "format": "Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.",
        "args": [
          {
            "type": "INT_LITERAL",
            "key": "NUM_SCRIPTS",
            "value": "1"
          },
          {
            "type": "INT_LITERAL",
            "key": "NUM_CSS",
            "value": "3"
          }
        ]
      },
      "urlBlocks": [
        {
          "header": {
            "format": "None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML."
          }
        },
        {
          "header": {
            "format": "{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:",
            "args": [
              {
                "type": "HYPERLINK",
                "key": "LINK",
                "value": "https://developers.google.com/speed/docs/insights/BlockingJS"
              }
            ]
          },
          "urls": [
            {
              "result": {
                "format": "{{URL}}",
                "args": [
                  {
                    "type": "URL",
                    "key": "URL",
                    "value": "value 1 output"
                  }
                ]
              }
            }
          ]
        },
        {
          "header": {
            "format": "{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:",
            "args": [
              {
                "type": "HYPERLINK",
                "key": "LINK",
                "value": "https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery"
              }
            ]
          },
          "urls": [
            {
              "result": {
                "format": "{{URL}}",
                "args": [
                  {
                    "type": "URL",
                    "key": "URL",
                    "value": "value 2 output"
                  }
                ]
              }
            },
            {
              "result": {
                "format": "{{URL}}",
                "args": [
                  {
                    "type": "URL",
                    "key": "URL",
                    "value": "value 3 output"
                  }
                ]
              }
            },
            {
              "result": {
                "format": "{{URL}}",
                "args": [
                  {
                    "type": "URL",
                    "key": "URL",
                    "value": "value 4 output"
                  }
                ]
              }
            }
          ]
        }
      ]
    },
    "PrioritizeVisibleContent": {
      "localizedRuleName": "Prioritize visible content",
      "ruleImpact": 0.0,
      "groups": [
        "SPEED"
      ],
      "summary": {
        "format": "You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.",
        "args": [
          {
            "type": "HYPERLINK",
            "key": "LINK",
            "value": "https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent"
          }
        ]
      }
    }
  }
}

Open in new window

0
Ganesh GuruduSenior ConsultantCommented:
Hello Christensen,

it seem your are doing wrong, is the code working? definitely it might have error.

it always work on name value pairs.

you may get output like this
localizedRuleName : Eliminate render-blocking JavaScript and CSS in above-the-fold content
ruleImpact: 12.0
groups:[SPEED]
summary:{\"format\":\"Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.\",\"args\":[{\"type\":\"INT_LITERAL\",\"key\":\"NUM_SCRIPTS\",\"value\":\"1\"},{\"type\":\"INT_LITERAL\",\"key\":\"NUM_CSS\",\"value\":\"3\"}]}
0
Ganesh GuruduSenior ConsultantCommented:
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Jesper ChristensenProgrammerAuthor Commented:
Hi guys.

Thanks for your reply.

Maybe I did not make myself clear

if I run my code, I get this output:
MinimizeRenderBlockingResources
PrioritizeVisibleContent

Bud I would like this output:
MinimizeRenderBlockingResources:
(Eliminate render-blocking JavaScript and CSS in above-the-fold content)
value 1 output
value 2 output
value 3 output
value 4 output

I can´t figure out how to loop through the json objects.
0
Ganesh GuruduSenior ConsultantCommented:
try using below code

Response.Write(item.Name+"<br>");

you need get into sub level like this. or use sub loop

foreach (var item in json.formattedResults.ruleResults.MinimizeRenderBlockingResources)
{
      Response.Write(item.Name+"<br>");
}
OR  like this

Response.Write(json.formattedResults.ruleResults(item).localizedRuleName+"<br>");
0
Jesper ChristensenProgrammerAuthor Commented:
Hi. Try insert my code to VS Studio? Then you will se, that your code returns the same as mine.

 
How do I loop through the json string and get the values I want? F.ex:
value 1 output
value 2 output
value 3 output
value 4 output
0
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
How do I loop through the json string and get the values I want? F.ex:
value 1 output
value 2 output
value 3 output
value 4 output
still not clear what do you mean by value 1 output? can you give a real example from your json value?
0
it_saigeDeveloperCommented:
Here is how you could do it:
using System;

namespace EE_Q29073719
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonstr = "{\"formattedResults\":{\"ruleResults\":{\"MinimizeRenderBlockingResources\":{\"localizedRuleName\":\"Eliminate render-blocking JavaScript and CSS in above-the-fold content\",\"ruleImpact\":12.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.\",\"args\":[{\"type\":\"INT_LITERAL\",\"key\":\"NUM_SCRIPTS\",\"value\":\"1\"},{\"type\":\"INT_LITERAL\",\"key\":\"NUM_CSS\",\"value\":\"3\"}]},\"urlBlocks\":[{\"header\":{\"format\":\"None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.\"}},{\"header\":{\"format\":\"{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/BlockingJS\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 1 output\"}]}}]},{\"header\":{\"format\":\"{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 2 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 3 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 4 output\"}]}}]}]},\"PrioritizeVisibleContent\":{\"localizedRuleName\":\"Prioritize visible content\",\"ruleImpact\":.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent\"}]}}}}}";
            dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonstr);
            foreach (var item in json.formattedResults.ruleResults)
            {
                Console.WriteLine(item.Name);
            }

            if (json?.formattedResults?.ruleResults?.MinimizeRenderBlockingResources?.urlBlocks != null)
            {
                foreach (var urlBlock in json.formattedResults.ruleResults.MinimizeRenderBlockingResources.urlBlocks)
                {
                    if (urlBlock.urls != null)
                    {
                        foreach (var url in urlBlock.urls)
                        {
                            if (url?.result?.args?[0]?.value != null)
                            {
                                Console.WriteLine(url.result.args[0].value);
                            }
                        }
                    }
                }
            }
            Console.ReadLine();
        }
    }
}

Open in new window

Which produces the following output -Capture.PNG
A better solution, however, would be to create distinct objects and map your json to those objects; e.g. -
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q29073719
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonstr = "{\"formattedResults\":{\"ruleResults\":{\"MinimizeRenderBlockingResources\":{\"localizedRuleName\":\"Eliminate render-blocking JavaScript and CSS in above-the-fold content\",\"ruleImpact\":12.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.\",\"args\":[{\"type\":\"INT_LITERAL\",\"key\":\"NUM_SCRIPTS\",\"value\":\"1\"},{\"type\":\"INT_LITERAL\",\"key\":\"NUM_CSS\",\"value\":\"3\"}]},\"urlBlocks\":[{\"header\":{\"format\":\"None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.\"}},{\"header\":{\"format\":\"{{BEGIN_LINK}}Remove render-blocking JavaScript{{END_LINK}}:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/BlockingJS\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 1 output\"}]}}]},{\"header\":{\"format\":\"{{BEGIN_LINK}}Optimize CSS Delivery{{END_LINK}} of the following:\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery\"}]},\"urls\":[{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 2 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 3 output\"}]}},{\"result\":{\"format\":\"{{URL}}\",\"args\":[{\"type\":\"URL\",\"key\":\"URL\",\"value\":\"value 4 output\"}]}}]}]},\"PrioritizeVisibleContent\":{\"localizedRuleName\":\"Prioritize visible content\",\"ruleImpact\":.0,\"groups\":[\"SPEED\"],\"summary\":{\"format\":\"You have the above-the-fold content properly prioritized. Learn more about {{BEGIN_LINK}}prioritizing visible content{{END_LINK}}.\",\"args\":[{\"type\":\"HYPERLINK\",\"key\":\"LINK\",\"value\":\"https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent\"}]}}}}}";
            Root json = JsonConvert.DeserializeObject<Root>(jsonstr);
            if (json?.formattedResults?.ruleResults != null)
            {
                foreach(var property in typeof(RuleResults).GetProperties())
                {
                    Console.WriteLine(property.Name);
                }

                Console.WriteLine(string.Join("\r\n", (from urlBlock in json.formattedResults.ruleResults.MinimizeRenderBlockingResources.urlBlocks
                                                       where urlBlock?.urls != null
                                                       from url in urlBlock.urls
                                                       where url?.result?.args?[0]?.value != null
                                                       select url.result.args[0].value)));
            }
            Console.ReadLine();
        }
    }

    class Root
    {
        public FormattedResults formattedResults { get; set; }
    }

    class FormattedResults
    {
        public RuleResults ruleResults { get; set; }
    }

    class RuleResults
    {
        public MinimizeRenderBlockingResources MinimizeRenderBlockingResources { get; set; }
        public PrioritizeVisibleContent PrioritizeVisibleContent { get; set; }
    }

    public class MinimizeRenderBlockingResources
    {
        public string localizedRuleName { get; set; }
        public double ruleImpact { get; set; }
        public List<string> groups { get; set; }
        public Summary summary { get; set; }
        public List<UrlBlock> urlBlocks { get; set; }
    }

    public class PrioritizeVisibleContent
    {
        public string localizedRuleName { get; set; }
        public double ruleImpact { get; set; }
        public List<string> groups { get; set; }
        public Summary summary { get; set; }
    }

    public class Summary
    {
        public string format { get; set; }
        public List<Argument> args { get; set; }
    }

    public class Argument
    {
        public string type { get; set; }
        public string key { get; set; }
        public string value { get; set; }
    }

    public class UrlBlock
    {
        public Arguments header { get; set; }
        public List<Url> urls { get; set; }
    }

    public class Url
    {
        public Arguments result { get; set; }
    }

    public class Arguments
    {
        public string format { get; set; }
        public List<Argument> args { get; set; }
    }
}

Open in new window

Which produces the same output as above.

-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jesper ChristensenProgrammerAuthor Commented:
Saige THANKS !!!!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
CSS

From novice to tech pro — start learning today.