Home > other >  Save JSON with Custom Column name and custom value
Save JSON with Custom Column name and custom value

Time:10-23

I have this code

foreach (var table in doc.DocumentNode.SelectNodes("//table[@id='formTbl']"))
{
    foreach (var row in table.SelectNodes("tbody/tr"))
    {
        foreach (var cell in row.SelectNodes("td"))
        {
            if (X == 1)
            { 
                Console.WriteLine($"Value: {cell.InnerText}");
                X = 2;
                string Value = cell.InnerText;
            }
            else if(X==2)
            {
                Console.WriteLine($"Column: {cell.InnerText}");
                X = 1;
                string Column = cell.InnerText;
            }                     
        }
    }
}                     

and I want to get Json like
{Column:Value, Column:Value, Column:Value}

I am using Newtonsoft.Json & HtmlAgilityPack. Is there any way to get that Json? So far I think I would be able to create
{ {X = Column, Y= Value}, {X = Column, Y= Value} } but it's not what I want.

E: Table looks like

<table>
    <tr>
        <td>Column1</td>
        <td>Value1</td>
    </tr>
    <tr>
        <td>Column2</td>
        <td>Value2</td>
    </tr>
    <tr>
        <td>Column3</td>
        <td>Value3</td>
    </tr>
    <tr>
        <td>Column4</td>
        <td>Value4</td>
    </tr>
</table>

CodePudding user response:

Provided your "Column" names were unique, you could simply use a Dictionary and serialize it. ie:

void Main()
{
    var html = 
@"<table id='formTbl'>
<tbody>
    <tr>
        <td>Column1</td>
        <td>Value1</td>
    </tr>
    <tr>
        <td>Column2</td>
        <td>Value2</td>
    </tr>
    <tr>
        <td>Column3</td>
        <td>Value3</td>
    </tr>
    <tr>
        <td>Column4</td>
        <td>Value4</td>
    </tr>
    </tbody>
</table>";
    var doc = new HtmlDocument();
    doc.LoadHtml(html);
    
    Dictionary<string, object> myDict = new Dictionary<string, object>();

    foreach (var table in doc.DocumentNode.SelectNodes("//table[@id='formTbl']"))
    {
        foreach (var row in table.SelectNodes("tbody/tr"))
        {
            var cells = row.SelectNodes("td");
            myDict.Add(cells[0].InnerText, cells[1].InnerText);
        }
    }
    var json = JsonConvert.SerializeObject(myDict, Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(json);
}

EDIT: This outputs:

{
  "Column1": "Value1",
  "Column2": "Value2",
  "Column3": "Value3",
  "Column4": "Value4"
}
  • Related