简体   繁体   中英

How to convert Json object of html element into actual HTML element that i can render on view using C# or js or jquery

My requirement is, i want to get a json(in the form of html tag) from DB and convert it into html.

{"input":{
"name":"fname",
"type":"text",
"placeholder":"Enter your firstname",
"Id":"fname"
 }
}

{"button" :{
"name":"btn",
"class":"save",
"type":"submit",
"Id":"btn1",
"text":"save"
 }
}

i want to convert this json into html tags like

<input type="text" id="fname" name="fname" placeholder="Enter your firstname">

<button type="submit" class="save" id="btn1" name="btn">save</button>

how can i convert this using c# or javascript or jquery anything will help me

To solve your problem you need to loop throw your json and createElement along the way.


let json = {
    "input": {
        "name": "fname",
        "type": "text",
        "placeholder": "Enter your firstname",
        "id": "fname"
    },
    "button" : {
        "name": "btn",
        "class": "save",
        "type": "submit",
        "id": "btn1",
        "text": "save"
    }
}

Object.keys(json).forEach( (element) => {
    let foo = document.createElement(element)

    Object.keys(json[element]).forEach( (nestedAttribute) => {
        foo.setAttribute(nestedAttribute, json[element][nestedAttribute]);
    })
    document.body.appendChild(foo)
})

Object.keys(json) allow you to get the keys of your json

This way the result looks like this:

在此处输入图像描述

Have a nice day !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM