iterate through JSON array with mustache - json

I am new to Mustache, please bear with me :)
I have an array in my JSON
"prop":{"brands":["nike","adidas","puma"]}
if I have the template like this
{{#prop}}
<b>{{brands}}</b>
{{prop}}
and I want to get something like:
<b>nike</b>
<b>adidas</b>
<b>puma</b>
I understand the elements in the array are not hash key-value pairs, however I am wondering if there is anyway in mustache that I can iterate through the elements.
Thanks!

Here is a working fiddle: http://jsfiddle.net/Qa4UX/
Basically, you need to iterate over the brands array.
Since your array is raw and does not have objects inside you have to reference each string like so:
{{#props}}
<ul>
{{#brands}}
<li>
{{#.}}
<b>{{.}}</b>
{{/.}}
</li>
{{/brands}}
</ul>
{{/props}}
You can also find many more examples over here: https://github.com/janl/mustache.js#mustachejs---logic-less-mustache-templates-with-javascript

This works
{{#json.props.brands}}
<h1>{{.}}</h1>
{{/json.props.brands}}
{{.}} When looping over an array of strings, a . can be used to refer to the current item in the list.

mustache is logicless, so writing your own iteration/loop in it is impossible. It is easy to convert your JSON though. For example:
var json = '{"prop":{"brands":["nike","adidas","puma"]}}';
var obj = JSON.parse(json);
var data = {brands: obj.prop['brands'].map(function(x){ return {name: x}; })};
Gives you a data variable which will work with the template:
{{#brands}}
<b>{{name}}</b>
{{/brands}}

Related

How to retrieve data from an external nested json file on seed.rb

I want to retrieve data from an external nested JSON file on my seed.rb
The JSON looks like this:
{"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}
I saw a solution on GitHub but it only works on non-nested JSON.
Let's say you have JSON file db/seeds.json:
{"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}
You can use it like this in your db/seeds.rb:
seeds = JSON.parse(Rails.root.join("db", "seeds.json"), symbolize_names: true)
User.create(seeds[:people])
seeds[:people] in this case is array of hashes with user attributes
if you have:
json_data = {"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}
when you do:
json_data[:people]
you'll get an array:
[{:name=>"John", :age=>"23"}, {:name=>"Jack", :age=>"25"}]
if you want to use this array to populate a model, you can do:
People.create(json_data[:people])
if you want to read each item values, you can iterate through your data, like:
json_data[:people].each {|p| puts p[:name], p[:age]}

Convert json to array using Perl

I have a chunk of json that has the following format:
{"page":{"size":7,"number":1,"totalPages":1,"totalElements":7,"resultSetId":null,"duration":0},"content":[{"id":"787edc99-e94f-4132-b596-d04fc56596f9","name":"Verification","attributes":{"ruleExecutionClass":"VerificationRule"},"userTags":[],"links":[{"rel":"self","href":"/endpoint/787edc99-e94f-4132-b596-d04fc56596f9","id":"787edc99-e94f-...
Basically the size attribute (in this case) tells me that there are 7 parts to the content section. How do I convert this chunk of json to an array in Perl, and can I do it using the size attribute? Or is there a simpler way like just using decode_json()?
Here is what I have so far:
my $resources = get_that_json_chunk(); # function returns exactly the json you see, except all 7 resources in the content section
my #decoded_json = #$resources;
foreach my $resource (#decoded_json) {
I've also tried something like this:
my $deserialize = from_json( $resources );
my #decoded_json = (#{$deserialize});
I want to iterate over the array and handle the data. I've tried a few different ways because I read a little about array refs, but I keep getting "Not an ARRAY reference" errors and "Can't use string ("{"page":{"size":7,"number":1,"to"...) as an ARRAY ref while "strict refs" in use"
Thank you to Matt Jacob:
my $deserialized = decode_json($resources);
print "$_->{id}\n" for #{$deserialized->{content}};

Angular ng-repeat without creating an element

Suppose I have this Json data in my controller:
var rootObj = [{
devices: ["device1", "device2"],
subGroups: [{devices: ["device3", "device4"]}, {devices: ["device5", "device6"]}]
}, {
devices: ["device7"],
subGroups: [{devices: ["device8"]}, {devices: ["device9"]}]
}];
And I want to show all devices in flat structure, like this:
<ul>
<li>device1</li>
<li>device2</li>
<li>device3</li>
<li>device4</li>
<li>device5</li>
<li>device6</li>
<li>device7</li>
<li>device8</li>
<li>device9</li>
</ul>
How can I use ng-repeat on rootObjto get above html?
I don't want to manipulate the original object, only using ng-repeat on rootObj.
The only option to solve it, is to use ng-repeat without creating any element on ng-repeat itself.
What is the best way to achieve it?
It achievable with black magic!
Returns
(Array): Returns the new flattened array.

In Scrapy how to seperate items in output json file

I am a new learner of Scrapy and encounter a problem. I get several json responses when crawling websites(that part I have already done). I want to fill them in items and then output to one json file. But the output file is not what I expected.
The item class looks like this:
class USLPlayer(scrapy.Item):
ln = scrapy.Field()
fn = scrapy.Field() ...
The original json file structure looks like this:
{"players":{"4752569":{"ln":"Musa","fn":"Yahaya", .... ,"apprvd":"59750"}, "4801435":{"ln":"Ackley","fn":"Brian", ... ,"apprvd":"59750"}, ...}}
The expected result I hope to be looks like this:
{"item" :{"ln":"Musa","fn":"Yahaya", .... ,"apprvd":"59750"}},{"item": {"ln":"Ackley","fn":"Brian", ... ,"apprvd":"59750"}, ...
Basically I hope every item should be separated list.
The code about fill item is:
players = json.loads(plain_text)
for id, player in players["players"].items():
for key, value in player.items():
item = USLPlayer() item[key] = value
yield item
Is there any way I can ouput json file as I expected. Thank you very much for kind answer.
Have you tried the JSON lines feed exporter?
It will output your items as JSON objects one per line. Then, reading the list of players from the file is as easy as using json.loads on each line.

Filtering and rearranging model/content in Ember Controllers

Let's say I have a JSON array of data, something like:
[ {"name":"parijat","age":28},
{"name":"paul","age":28},
{"name":"steven","age"27},
...
]
that is part of my model, and this model is setup like this:
App.UserRoute = Ember.Route.extend({
model:function(){
return App.User.FIXTURES ; // defined above
}
});
I want to get the unique ages from this JSON array and display them in my template, so I reference the computed properties article and read up a little on how to enumerate Ember Enumerables, to eventually get this:
App.UserController = Ember.ArrayController.extend({
ages:function(){
var data = this.get('content');
var ages = data.filter(function(item){
return item.age;
});
}.property('content');
});
Now the above piece of code for controller is not correct but the problem is that it doesn't even go into data.filter() method if I add a console.log statements inside. IMO, it should typically be console logging as many times as there exist a App.Users.FIXTURE. I tried using property('content.#each') which did not work either. Nor did changing this.get('content') to this.get('content.#each') or this.get('content.#each').toArray() {spat an error}.
Not sure what to do here or what I am completely missing.
Filter is used for reducing the number of items, not for mapping.
You can use data.mapBy('age') to get an array of your ages:
ages:function(){
return this.get('content').mapBy('age');
}.property('content.#each')
or in your handlebars function you can just use the each helper:
{{#each item in controller}}
{{item.age}}
{{/each}}