0

I know asking a question without some code to show for it is frowned upon, but iam at a complete loss. I have simple JSON files like this for example (this is simplified but the the general structure is indentical):

[{
    "key1" : "some value",
    "key2" : 123
},{
    "key1" : "some other value",
    "key3"  : [
        "arrayVal1",
        "arrayVal2"
    ]
}]

How could i turn it into a HTML table something like this?

+----------+-------+---------+
| key1     | key2  | key3    | < this should be a th
+----------+-------+---------+
|some value| 123   |         |
+----------+-------+---------+
|some ot...|       |arrayVal1|
|          |       |arrayVal2|
+----------+-------+---------+

Sidenote: i have no idea what the names of the keys are and what kind of values (string, number, array) they hold in advance.

I can upload and parse the json files on the site, so thats not an issue here, just got no idea how to show them.

val
  • 729
  • 6
  • 19
  • Do you have something in mind regarding to javascript framworks? I know that jquery or knockout can do it in a couple of minutes. Let me know if you like knockout and I can give you a snippet code, I mention frameworks, because doing this with old style javascript will be a pain and does not worth the effort – rdarioduarte Feb 02 '16 at 13:41
  • 1
    what exactly is your problem? you cant cycle through json? you cant get the key names? you cant append html to your body? – Milan Halada Feb 02 '16 at 13:42
  • how do i cycle though the json getting the keys and values, how do i figure out if the value is an array? (because i'll need to print them the way in the question) how do i add a new tr if there's a key that doesnt exist yet? – val Feb 02 '16 at 13:46
  • Do you know the number of columns in advance and what type of data is stored in each? – Yogi Feb 02 '16 at 13:54
  • no, but they can only be string, numbers, an array of string and array of numbers, nothing nested. – val Feb 02 '16 at 13:55
  • 1
    See: [Check if object is array?](http://stackoverflow.com/questions/4775722/check-if-object-is-array) and [Get array of object's keys](http://stackoverflow.com/questions/8763125/get-array-of-objects-keys). Also see: javascript [typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) which would be very useful. – Yogi Feb 02 '16 at 13:56

1 Answers1

1

For future historians: Here is a working code. It might look like butt, and has code duplication everywhere, but it works. Thanks for Roberto for pointing out some helpful threads.

Community
  • 1
  • 1
val
  • 729
  • 6
  • 19