-1

How can I get appsettings.json data by using Microsoft.Extensions.Configuration? My appsettings.json file is:

"Test": [
  {
    "A": "101",
    "B": "6390"
  },
  {
    "A": "101",
    "B": "6391"
  },
  {
    "A": "101",
    "B": "6392"
  }
]

when is use

Configuration.GetSection("Test").GetChildren()

I get the error:

System.Linq.Enumerable+SelectEnumerableIterator`2[System.String.Microsoft.Extensions.Configuration.IConfigurationSection]

I cannot understand how to proceed with this error. Please ask if any info needed. The question is not a duplicate as i cannot run the code properly and it stops debugging and gives the error i mentioned.

Oh, and the actual error (as shown by the console) was:

Uncaught SyntaxError: Invalid or unexpected token

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
user
  • 21
  • 6
  • 1
    Possible duplicate of [how to get value from appsettings.json](https://stackoverflow.com/questions/43757189/how-to-get-value-from-appsettings-json) – AmirNorouzpour May 14 '18 at 06:46
  • Possible duplicate of [Getting value from appsettings.json in .net core](https://stackoverflow.com/questions/46940710/getting-value-from-appsettings-json-in-net-core) – Saadi May 14 '18 at 06:47
  • not working for me – user May 14 '18 at 06:47
  • 1
    What you provided as "the error" is not an error but an internal iterator type name. Please review&correct. Also, **Really please** do not post text as images. Please paste text as text, especially that important texts like in this case ("here, see the error I got"... and image.. so we cant even copy the name and google it for you, etc, ignoring the fact that image was just wrong). This time I took the effort to read the image and write the text from the image by hand. – quetzalcoatl May 14 '18 at 06:48
  • "not working for me" - "not working" is a rather broad term. Does it work but return not the things you wanted? Did it not work at all? Were there any errors? At compilation or at runtime? What's not working? – quetzalcoatl May 14 '18 at 06:49
  • Finally, IIRC, the appsettings.json file is **required** to have a j-object at the root scope. You have a key-value pair. Please try adding brackets { } around all your text in the json file. It should look like `{ "Test": [ ....items... ] }` – quetzalcoatl May 14 '18 at 06:53
  • Not working for me as in i cannot get the results. when i run the project the debugging stops at the error i mentioned and cannot figure out why does it stop. – user May 14 '18 at 06:56
  • @quetzalcoatl done that. still the same error continues – user May 14 '18 at 06:56
  • the console shows that `Uncaught SyntaxError: Invalid or unexpected token` – user May 14 '18 at 06:58
  • @user: This means your input JSON file is broken. Inspect it CAREFULLY. Watch out for any spurious commas, dots, missing quotes, etc. If you post it _all_, we may be able to help you with it. Or just open it in VisualStudio and see where you get the red syntax markers.. – quetzalcoatl May 14 '18 at 06:59
  • @user: Or paste it here and see what the syntax checker says.. https://jsonlint.com – quetzalcoatl May 14 '18 at 07:00
  • the syntax checker says that it is a valid json. – user May 14 '18 at 07:03
  • @user: ok, and what does VisualStudio say when you open that json in VisualStudio? if the text is OK but the actual file is damaged, VS will tell you.. Anyways, if VS says it's OK, then then you have either: (a) failed to save the file properly (forgot to save? saved in weird encording instead of UTF8?/etc), (b) mistook one appsettings file for another (like, you edit `appsettings.json` but error is in `appsettings.Development.json`), (c) mistook project directories (like VS reads c:/myproject and you're editing desktop/myproject), ...or some similar thing. – quetzalcoatl May 14 '18 at 07:05
  • it is working fine if i paste the json and iterate through it in my code. but i want that json should be loaded externally so i pasted the json in appsettings.json file. but i cannot understand how to load my json from that file into my code – user May 14 '18 at 07:07
  • `Configuration.GetSection("Test")` if i use only this than the error is `Microsoft is not defined` . i cannot understand the error/ – user May 14 '18 at 07:12
  • The errors and symptoms you provide are all mixed up, hard to say. It now sounds a tiny bit like compiler complaining on the line of `using Microsoft.Extensions.Configuration`. If so, then you've forgot to use some add-reference or your project is missing a nuget reference. This may also indicate that you failed to notice that you're using "wrong C# version" (quotes because it's totally wrong to say it like that right now), like, your project is WPF and the code snippet to get JSON is from ASP-CORE -- but any such is out of scope of initial JSON syntax problem. New problem, ask new question. – quetzalcoatl May 14 '18 at 07:21
  • I have created an answer does this solve the problem? – Timon Post May 14 '18 at 07:40

2 Answers2

0

Considering the tiny info you provided, maybe you just have a typo.

IIRC, the appsettings.json file is required to have a j-object at the root scope. Maybe a j-array is OK. I don't remember. But what you have is a key-value pair. A slice of an object. Most of JSON parsers will simply fail on such input. Please try adding brackets { } around all your text in the json file:

{   //<--- added
  "Test": [
    {
      "A": "101",
      "B": "6390"
    },
    ....
  ]
}   //<--- added
quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
0

First thing to do is to change your json and add the brackets:

{
  "Test": [
      {
        "A": "101",
        "B": "6390"
      },
      {
        "A": "101",
        "B": "6391"
      },
      {
        "A": "101",
        "B": "6392"
      }
  ]
}

Before you can read your settings with IConfiguration add the following refrences, you can do that with nuget packet manager:

enter image description here

Than you can do the following:

 // This class can be used for managing your AppSettings file.
class AppSettings
{
    private readonly IConfiguration configuration;

    public AppSettings(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

    // Get the value at an specific key.
    public string GetValue(string key)
    {
        return configuration[key];
    }
}

class Program
{
    // This can be used for getting an configuration builder for your config file. Pass in the config name.
    public static IConfigurationBuilder LoadConfiguration(string configFileName)
    {
        // get the file from the current directory and create an builder from it.
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
            .AddJsonFile(configFileName);

        return builder;

    }

    static void Main(string[] args)
    {
        // create configuration builder.
        var configuration = LoadConfiguration("appsettings.json");

        // create your AppSettings class and pass the IConfiguration object.
        AppSettings appConfig = new AppSettings(configuration.Build());

        // read the value.
        var firstItemAValue = appConfig.GetValue("Test:0:A");
        var secondItemBValue = appConfig.GetValue("Test:1:B");

    }
}
Timon Post
  • 2,779
  • 1
  • 17
  • 32