0

I have been working with json files and angularjs,since i made changes to the json file to make it more complete with information, the structure of the file became more complex, now i can't access the data they way i used to. It's supposed to be the same way but it's not loading.

this is the jason: http://www.jsoneditoronline.org/?id=72e10a49f6f7650a864dda13a3f2d56a, (Note: estado=state, localidad=location i'm trying to display the locations from various states in a chosen select).

How i load json data into the html:

<select class="control-group chosen-select" chosen id='sl_edo'  style="width:300px;">
  <!-- also i tried ng-repeat="pueblo in pueblos" which worked with the old json file-->
        <optgroup ng-repeat="pueblo in pueblos[0] | orderBy:'estado'" label={{pueblo.estado}}>
          <option>{{pueblo.localidad}}</option>

        </optgroup>

  </select>

some tests i did to check how is the data structure

 <p>{{pueblos[0].estado}}</p>

This line brings me this

[{"Jalisco":{"localidad":{"Tequila":,etc...

another html line i tested

<p>{{pueblos[0]}}</p>

{"estado":[{"Jalisco":{"localidad":{"Tequila"

1
  • 1
    The key "pueblos" occurs nowhere in that file. Each estado has an object of localidad keyed on city name. Just look at the JSON and adjust your code accordingly. You might think it should be the same way, but it is not. Commented Sep 1, 2015 at 17:39

1 Answer 1

2

Your data structures are a little off. You want similar objects to have the same structure. For instance, right now, to access the "Jalisco" object, you have to call pueblos[0].estado[0].Jalisco or pueblos[0].estado[0]["Jalisco"]. But if you try pueblos[0].estado[1].Jalisco, you get an error, because estado[1] only has "Sonora" as an attribute. Instead, you probably want a structure like this:

estados = [
    {
        "nombre": "Jalisco",
        "localidades": [
            {
                "nombre": "Tequila",
                "oferta": {
                    "gen": 99,
                    "ecas": 66,
                },
            },
        ],
    }
]

In this structure, you can access the name of the state by estado[#idx].nombre. Then if you want that state's localitities, it's estado[#idx].localidades[#idx]. So if you want the "gen" attribute of the "oferta" in Tequila, you access it like this, estados[0].localidades[0].oferta.gen. Basically, if you're working with a list that you loop over using ng-repeat, all the objects should share the same attribute names. You should never use distinct names as attribute names, like using "Jalisco" or "Sonora" as attributes.

Sign up to request clarification or add additional context in comments.

Comments

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.