Search code examples
htmlarraysstringpre

Converting a massive string in a table format to a table


Say a webpage has this as the only thing on it:

<pre style="word-wrap: break-word; white-space: pre-wrap;">
"[{"Asset":1112, "Name":"Test"}, {"Asset":223, "Name":"Drill"}]"
</pre>

How would I turn that string into a table that I can access and draw from? Even even if I find it, I still have no clue how to convert the string into a table that I access.

I know that document.getElementsByTagName("PRE"); will return the massive string, but I'm a little lost after that.

I was searching through hundreds of pages trying to find a good example for what I need to do. Here is one such example: http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&LegendExpanded=true&Category=2&PageNumber=1


Solution

  • This is a classic JSON parsing problem. The page you linked is actually text only - the pre formatting you're seeing is only the browser's default styling. If you view page source, you will be able to see that the page is pure text only JSON.

    So what you will need to do is to fetch that page into your application using an XMLHttpRequest, then once you have the string you will be able to parse it using the inbuilt JSON utilities.

    Here is a Live Demo showing you how to turn the raw JSON string data into a usable data structure once you have it in your application:

    var str = '[{"Asset":1112, "Name":"Test"}, {"Asset":223, "Name":"Drill"}]';
    var obj = JSON.parse(str);
    var output = "Asset 1: " + obj[0].Asset + ", Name: " + obj[0].Name + "<br />";
    output += "Asset 2: " + obj[1].Asset + ", Name: " + obj[1].Name;
    document.getElementById("output").innerHTML = output;
    <div id="output"></div>

    JSFiddle Version: https://jsfiddle.net/q0wdz4vz/1/

    Note that the outer JSON object is an array. For the first line I used obj[0] to retrieve the first object in the array, then used .Asset to get its asset number. Likewise with .Name, and the second object.