문제

var json = {
"color" : {
    "off-white" : {
        "inactive" : 0,
        "instock" : 5,
        "prestock" : 49
    },
    "red" : {
        "prestock" : 50,
        "instock" : 10,
        "inactive" : 0
    }
  }
};

In Javascript if I do

  for (var col in json.color) {
      result += col  + " = " + JSON.stringify(json.color[col].prestock)+ "\n";
  }

I can get "off-white" and "red" and all the sub-documents.

I did the same thing but it won't give me the same outputs. What else can i do?

to get the outputs of "off-white" and "red" i have to

{% for col in Object.keys(json.color) %}

but i can't access to sub-documents.

If I do

{% for col in json.color %}
<li>{{Object.keys(col)}}</li>

I get

  • "off-white", "red"
  • I need them separately, like:

  • off-white
  • red
  • Thanks! Merry Christmas and Happy New Year

    도움이 되었습니까?

    해결책

    In swig, you can get both the key and the value without using Object.keys:

    {% for key, val in json.color %}
      <li>{{ key }} = {{ val.prestock }}</li>
    {% endfor %}
    

    That should give you the same thing you're asking for in the JavaScript example.

    다른 팁

    In JavaScript you should do like

    json.color.off-white  OR json['color']['off-white']
    

    // it will give you an object like

    {
       "inactive" : 0,
       "instock" : 5,
       "prestock" : 49
    }
    
    // check  alert(JSON.stringify(json.color.off-white));
    

    This won't return an Array so you won't be able to loop through it.

    further you can get value of inactive by accessing object like json.color.off-white.inactive

    So to separately display them I think you need do something like this:

    {% for key in Object.keys(json.color) %}
      <li>{{ key }},{{json["color"][key]["prestock"]}}</li>
    {% endfor %}
    

    Sorry, I suppose you already have the color keys. Now I update the code, hope works.

    라이센스 : CC-BY-SA ~와 함께 속성
    제휴하지 않습니다 StackOverflow
    scroll top