JSON Question

hi all,

for automatically loading items via the page.children i created an page.json.twig template. if i call the file directly via “http://server.com/page.json” the *.json file is parsed like it should.

if an element inside the code calls for the json file via javascript some numbers and so are added to the file uri (http://server.com/page.json?_22344234) and an error appears that this file can not be found.

what could be a solution for this? thanks very much.

how are you calling the page via javascript? Can you paste a sample of that code?

Also can you please include your code snippets in markdown backticks? or code blocks? (see the question mark in top right of the text-entry box on this forum for help).

i call it via the data-json=“portfolio.json” attribute in the html code. i dont se markdown at all.

in the js i use
—js
if( $(’.page’).length ) {
var pageJSON = $(’.page[data-json]’);
var pageData = ‘’;
var $page = $(’.page’);

	if( pageJSON.length ) {
		$.ajax({
	    	url: pageJSON.attr('data-json'),
			cache: false,
			success: function(data) {
				pageData = data;

page = portfolio

what happens if you set cache: true or remove that bit? I don’t think Grav has anything to do with this checksum data appended after the .json part.

ok i will try. i wondered that calling directly in browser works but in attribute not. so i have to check the javascript. thanks

ok this was/is the reason. the parsed json is not valid and i have no clue how to get {{ page.title }} and so on in an array to let jsonencode via twig work…

Here’s what we have in the simplesearch plugin’s simplesearch_resultsjson.twig file:

{"results":[
{%- for search_result in search_results -%}
{{- search_result.route|json_encode -}},{{ not loop.last ? ',' }}
{%- endfor -%}
]}

Basically we are constructing an results array and using the |json_encode twig filter to ensure it’s in the correct json format.

i have something like this
—twig
[
{% for page in page.children %}
{
“image”: “{{ page.media.images|first.url }}”,
“name”: “{{ page.title }}”,
“categories”: [“Logo”],
“url”: “{{ page.url }}”
{% if not loop.last %}
},
{% else%}
}
{% endif %}
{% endfor %}
]


but the json format is not valid becaus of curly braces

ok right now i change the indentation and it works. so the first image is pulled out of the folder, the title, the categories out of the taxonomy tags and the url of the page
—twig
[
{% for page in page.children %}
{
“image”: “{{ page.media.images|first.url }}”,
“name”: “{{ page.title }}”,
“categories”: [{% for tag in page.taxonomy.tag %}"{{ tag }}"{% if not loop.last %}, {% endif %},{% endfor %}],
“url”: “{{ page.url }}”
{% if not loop.last %}
},
{% else%}
}
{% endif %}
{% endfor %}
]


maybe this post will help other users to deal with it. thanks for your help :)

nice!

You could try spaceless also:

http://twig.sensiolabs.org/doc/tags/spaceless.html

ok nice to know. twig has a lot of options which i have to dig in deeper :slight_smile: