[PYTHON] Read json in C # and convert to dictionary type (forced)

Long time no see.

It's been a long time, everyone at Qiita. It's been a long time since the last time, but since then I bought a new computer. And I got tired of Python, so I decided to try C #.

Write it down as a memo to understand. Please forgive the gabber points.

About reading json that I thought

I used to use json in Python to store configuration files and data that had to be defined in json for convenience, so I definitely wanted to use it in C # as well. I was a little aware, but I was wondering what a great library Python has.

json loading code

hoge.json


{
  "hoge": "hoge1",
  "hogehoge": "hoge2",
  "hogehogehoge": "hoge3"
}

Although loading json in Python uses the json library

import json

def load_json(filename):
    with open(filename) as files:
        load = json.load(files)

    return load

If you define one function like this, it will come back as a dictionary type.

result = load_json("hoge.json")

hoge1 = result["hoge"]
hoge2 = result["hogehoge"]
hoge3 = result["hogehogehoge"]

print(hoge1)
print(hoge2)
print(hoge3)

print(type(hoge1))
print(type(hoge2))
print(type(hoge3))

hoge1
hoge2
hoge3
<class 'str'>
<class 'str'>
<class 'str'>

If you do this, you can easily return with str or int, so you can easily use it if you boil or bake it. (Gabber Code Degomen)

For C #

using System;
using System.IO;
using System.Text;
using System.Text.Json;

namespace ConsoleApp2
{
    class Program
    {
        public static string ReadAllLine(string filePath, string encodingName)
        {
            StreamReader sr = new StreamReader(filePath, Encoding.GetEncoding(encodingName));
            string allLine = sr.ReadToEnd();
            sr.Close();

            return allLine;
        }

        class hogejson
        {
            public string hoge { get; set; }
            public string hogehoge { get; set; }
            public string hogehogehoge { get; set; }
        }
        static void Main(string[] args)
        {
            string readjson = ReadAllLine("hoge.json", "utf-8");

            hogejson jsonData = JsonSerializer.Deserialize<hogejson>(readjson);

            string hoge = jsonData.hoge;
            string hogehoge = jsonData.hogehoge;
            string hogehogehoge = jsonData.hogehogehoge;

            Console.WriteLine(hoge);
            Console.WriteLine(hogehoge);
            Console.WriteLine(hogehogehoge);

            Console.WriteLine(hoge.GetType());
            Console.WriteLine(hogehoge.GetType());
            Console.WriteLine(hogehogehoge.GetType());

        }
    }
}
hoge1
hoge2
hoge3
System.String
System.String
System.String

If you do not write it like this, it will not read well, but the most personally troublesome thing is ** "I have to create a json class" ** Noto ** "It's hard to understand when I make a method (a function in Python (although it's a little different))! I got caught.

Why did this happen

In Python, the return value returned by the previous function must be ** dictionary type **, while in C #, ** specific return value ** must be specified. For this reason, in Python, it comes back as a dictionary type.

hoge = result["hoge"]

You can retrieve the value "hoge1" of the key "hoge" just by specifying it in and result. On the other hand, C # is set to hoge of class "hogejson" as string type (str) when the value of "hoge" which is the key of "hoge.json" is "hoge1". On the contrary, if you try to set this with an int type or another type, you cannot.

This is because the return value of class hoge is determined to be string. Therefore, since it is not specified as a return value in the dictionary type that was often taken care of in Python, even if the return value is specified as a dictionary type "arbitrarily", not only the keys of other "hogehoge" and "hogehogehoge" but also the value I don't even have the information (self-interpretation)

Let's make it so that it returns to the dictionary type! Lol

When I searched for it, it seems that there is a "Dictionary class" in C #, so it can be used in the same way as Python's dictionary type.

Then the story is quick, here is the result of repeated trial and error so that the key and value of hoge.json can be packed in a dictionary type.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;

namespace ConsoleApp2
{
    class library
    {
        //File reading
        public string ReadAllLine(string filePath, string encodingName)
        {
            StreamReader sr = new StreamReader(filePath, Encoding.GetEncoding(encodingName));
            string allLine = sr.ReadToEnd();
            sr.Close();

            return allLine;
        }

        //Forcibly convert List type to Dictionary type
        public static Dictionary<string, string> ListInDictionary(string[] left, string[] right)
        {
            
            //When they match
            if (left.Length == right.Length)
            {

                var result = new Dictionary<string, string>();

                //Turn for by the number of Lists on the left
                for (int i = 0; i < left.Length; i++)
                {
                    
                    //Add dictionary to result
                    result.Add(left[i], right[i]);
                }

                return result;

            }
            
            //When there is a discrepancy
            else
            {
                return null;
            }
        }

        class hogejson
        {
            public string hoge { get; set; }
            public string hogehoge { get; set; }
            public string hogehogehoge { get; set; }
        }
        //hoge.Method to load json
        public Dictionary<string, string> GetHogejson(string filename)
        {
            try
            {
                string jsonfile = ReadAllLine(filename, "utf-8");

                hogejson jsonData = JsonSerializer.Deserialize<hogejson>(jsonfile);

                string[] json_key = { "hoge", "hogehoge", "hogehogehoge" };
                string[] json_value = { jsonData.hoge, jsonData.hogehoge, jsonData.hogehogehoge };

                var result = ListInDictionary(json_key, json_value);

                return result;
            }

            //When json cannot be read
            catch (JsonException)
            {
                return null;
            }

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            library Library = new library();

            Dictionary<string, string> gethogejson = Library.GetHogejson("hoge.json");

            string hoge, hogehoge, hogehogehoge;

            hoge = gethogejson["hoge"];
            hogehoge = gethogejson["hogehoge"];
            hogehogehoge = gethogejson["hogehogehoge"];

            Console.WriteLine(hoge);
            Console.WriteLine(hogehoge);
            Console.WriteLine(hogehogehoge);

            Console.WriteLine(hoge.GetType());
            Console.WriteLine(hogehoge.GetType());
            Console.WriteLine(hogehogehoge.GetType());

        }
    }
}

... I felt it too aggressively ...

problem

  1. ** Regardless of whether the value is int type or not, make it string type and store it in result (dictionary type). ** **
  2. After all, I have to specify the class of json data, so I haven't reached a fundamental solution.
  3. I made it forcibly with the idea and wisdom that I came up with, so I got angry when I saw it.

Personally, I'm most grateful that it can be used like Python, but I feel like it's too aggressive and angry.

By the way, the result is

hoge1
hoge2
hoge3
System.String
System.String
System.String

It will be displayed like this.

Finally

If you find something like "This is better than this method ~~~ Gabber too much, use this ~~", don't hesitate to comment! I was in serious trouble, so I will try to improve it if I have time.

Postscript What is this? It often comes out and gets stuck. In this case, there is no choice but to save and restart it, which is very inconvenient. Screenshot_11.png

I wrote it down after a long time. good night.

Quote source

https://usefuledge.com/csharp-json.html https://json2csharp.com/ (The site that creates the json data class based on the json data, which is very convenient) Thank you!!!!!

Recommended Posts

Read json in C # and convert to dictionary type (forced)
Read big endian binary in Python and convert it to ndarray
Read and write JSON files in Python
How to generate permutations in Python and C ++
Convert UTF-8 CSV files to read in Excel
How to read JSON
Convert json to excel
Convert timezoned date and time to Unixtime in Python2.7
Reasons to use long type in SQLite3 (C # Mono.Data.Sqlite)
Convert / return class object to JSON format in Python
Convert Webpay Entity type to Dict type (recursively in Python)
Go language to see and remember Part 7 C language in GO language
C / Python> Read fwrite () value in C in Python> v0.1: 1 value / v0.2: 3 values / v0.3: corresponds to size_t / v0.4: Read double complex type
Tips for coding short and easy to read in Python
How to create and use static / dynamic libraries in C
I tried to illustrate the time and time in C language
How to get all the keys and values in the dictionary
I want to make the Dictionary type in the List unique
Object-oriented in C: Refactored "○ ✕ game" and ported it to Python
Determine the date and time format in Python and convert to Unixtime
Convert Tweepy Status object to JSON
Convert markdown to PDF in Python
How to convert 0.5 to 1056964608 in one shot
Preserve and read order in PyYAML
How to wrap C in Python
Python logging and dump to json
Ignore # line and read in pandas
Create and read messagepacks in Python
Play to predict race value and type from Pokemon name in TensorFlow
Read CSV file with Python and convert it to DataFrame as it is
Convert Python> two value sequence to dictionary
How to convert csv to tsv in CLI
Implement FIR filters in Python and C
Bind to class to read and write YAML
Convert (compress) formatted JSON string to 1-line JSON
Convert psd file to png in Python
Convert Excel data to JSON with python
Read Python csv and export to txt
[Introduction to Udemy Python3 + Application] 24. Dictionary type
Convert array (struct) to json with golang
How to convert DateTimeField format in Django
Convert from Markdown to HTML in Python
How to read CSV files in Pandas
How to use is and == in Python
Convert absolute URLs to relative URLs in Python
Books on data science to read in 2020
Sorting AtCoder ARC 086 C hashes to solve in Ruby, Perl, Java and Python
I'm addicted to the difference in how Flask and Django receive JSON data
How to read a serial number file in a loop, process it, and graph it
Difference in writing method to read external source code between Ruby and Python
Type notes to Python scripts for running PyTorch model in C ++ with libtorch