How to properly call and display .json file (alpine.js)?

Hello everyone

I’d like to call .json file and display it’s contents on a webpage. I’m using alpine.js for that
my page is located at :

https://ember.2038.io/slider.html

Hopefully someone will tell me what I’m doing wrong. :upside_down_face:

You are trying to loop an object. You need to loop the array inside the object.

<template x-for="item in data.white">
  <li x-text="item"></li>
</template>

thank you very much.

why it doesnt produce the same when i switch with data.black?

                          <template x-for="item in data.white">
                            <li x-text="item"></li>
                          </template>
                          <template x-for="item in data.black">
                            <li x-text="item"></li>
                          </template>

instead I get

object Object

white is an array of strings, black is an array of objects. You have to access the text or pick properties on the object.

could you please show me how

item inside the loop is an object. It has two properties on it. You need to dot . onto the property (or use bracket notation).

const black = [
  {
    text: "Ain't it nifty? Barb and Bob hit 50! So get off your ass and raise a glass to 50 years of _.",
    pick: 1,
  },
];

How would you access the text property on the object inside this array?

Accessing Object Properties with Dot Notation

// Only change code below this line

const hatValue = testObj.hat;    
const shirtValue = testObj.shirt;

so I tried with
<template x-for="item in data.black.text">
but no?

With the code you posted.

<template x-for="item in data.black">
  <li x-text="item"></li>
</template>

You have already dotted onto data.black in the loop, the item variable is each of the objects. So it is item.someProperty in the loop body.

OH! now I understand! thank you very much.

Happy to help.

If this isn’t super clear and you haven’t gone through the freeCodeCamp JS curriculum, I would highly suggest doing so.

I’ve gone through it quite long ago & it’s been a while since I touched js.

I additionally saw that this is happening

I have solved politics…\nMy solution is _.

Is this due to json file being poorly written or can I do something about this?

They are escaped newlines.

You can run replace on the strings.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.