0

Could anyone tell me how I would go about displaying the following json in html? The problem I am facing is that the sections have different string fields - for example the first only has 3 (name, quantity and card) and the next has 4. I'm going to write titles beside each one (The name: One, Quantity: 50 etc) but I don't want to display the title if the string field does not exist

  {
        "products": [
            {
                "name": "One",
                "quantity": 50,
                "type": "card"
            },

             {
                "name": "Two",
                "thumbnail": "us.jpg",
                "quantity": 50,
                "type": "card"
            },
            {
                "name": "Three",
                "thumbnail": "thumb.jpg",

            }
        ]
    }

Any ideas or advice?

Many thanks

2 Answers 2

1

Depends on what you actually want to do with given data - however, you can walk through the object by using for, as:

var json = {a: 5, b: 6, c: "aaa"}

for (var index in json)
    console.log(index+" "+json[index]);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you - but how would I do this if I wanted to display using different titles? So in your example, instead of say a : 5 being printed, I would print "Number : 5" So my title would replace the index
That's where depends on what you actually want to do kicks in. You'd need to place some conditions depending upon the value of the index. Like for example: typeof json[index] == "number" ? "Number" : index
Ok thanks again, I dont actually want to check what the type is. What I want to do is if the index is 'name' as per my code above - then I want to display some thing like "The name : One" - does that make sense?
Like this? index == "name" ? "The name" : index
1

Couple of loops 'ought to do the trick:

for (var i = 0; i < data.products.length; i++) {
    for (var key in data.products[i]) {
        //looping keys, rather than log, append to HTML somewhere
        console.log(key + ":" + data.products[i][key]); 
    }
}

1 Comment

Thank you - but what if I want to set my own names where the index is being set - for example, if the index name is 'quantity' , I'd like to replace the name as 'Amount' so it would display 'Amount : 50' - does that make sense?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.