How to manipulate a JSONArray in JQuery - javascript

i have a php function which returns me this code in JSON
{"0":{"title":"Dans l\u2019appartement"},"1":{"title":"A l\u2019a\u00e9roport - D\u00e9part de B\u00e9atrice"},"2":{"title":"Visite chez Jean-Louis"},"3":{"title":"Anita \u00e0 la matenit\u00e9"},"4":{"title":"Visite chez Jean-Louis 2"},"5":{"title":"H\u00e9l\u00e9na pr\u00e9sent\u00e9e \u00e0 la famille"},"6":{"title":"Chez des proches"},"7":{"title":"Soir\u00e9e souvenir avec un proche - Photos, histoires"},"8":{"title":"Douceline tenant un b\u00e9b\u00e9"},"9":{"title":"Visite chez Jean-Louis 3"},"10":{"title":"Bapt\u00eame de Alexandra - Dans l\u2019\u00e9glise"}}
and i want to manipulated in JQuery I’ve did this but it doesn’t work
$.each(json, function(item, value) {
console.log(value);
$.each(value, function() {
console.log(this.title);
});
});
any ideas thanks a lot

The first traversal using each provides you the object containing the value of title field.
So , Simply fetch the value using :
$.each(json, function(item, value) {
alert(value.title);
});
And here is the demo jsfiddle

Related

Find an item and place it on my shopping cart

I'm learning both javascript and cypress, and I need your help, please... I want to find an item on a page, and add that item to the shoping cart.
I don't understand why I don't get any answer after .find. I don't get an error on cypress, but the item it's never added to the cart, and the cy.log dont display anyting.
/// <reference types="Cypress"/>
it ('ContarElementos', () => {
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares').should('have.length', 6)
})
it ('Agregar elemento "top" al carrito de compra desde la pagina principal', function (){
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares')
.find ('.inventory_item_name')
.each(($el,index,$list) => {
if($el.attr('.inventory_item_name') == 'Sauce Labs Onesie'){
cy.log ('Se encontró lo buscado')
cy.get ('#ProductosPopulares').eq(index).contains('ADD TO CART').click()
}
})
})
})
I know the place that has the item, so if I place it like this, it find appears on the cart, but I need it to work if I dont know the place on the list.
it ('Agregar elemento "top" al carrito de compra desde la pagina principal', function (){
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares')
.find ('.inventory_item_name')
.each(($el,index,$list) => {
if($el.attr('.inventory_item_name') == 'Sauce Labs Onesie'){
cy.log ('Se encontró lo buscado')
}
})
cy.get ('#ProductosPopulares').eq(5).contains('ADD TO CART').click()
})
There is a mix-up between text and attribute, try swapping the .find() command and the .contains() command.
Something like this:
cy.contains('.inventory_list .inventory_item', 'Sauce Labs Onesie')
.find('button:contains("ADD TO CART")').click()

i18n, javascript - is there a way to use a 2nd file for the differences?

I would like to use, as I am doing now, one file for my primary language and a second file for english.
This is working great.
Now I would like to add two more files. One with just the changes compared to the primary language and a second one for the other language.
In other word..the first file is a big file with all the dictionary but for a specific customer i need some words to be translated differently. Instead of writing another file 99% equal to the original I just would like to write the different words.
How can I do that?
this is my code:
var i18nextInstance = i18next
.use(i18nextXHRBackend)
.use(i18nextBrowserLanguageDetector)
.init(
{
detection: {
// Escludo localStorage. Praticamente ricorda l'ultima lingua usata.
//order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
order: ['querystring', 'cookie', 'navigator', 'htmlTag'],
},
fallbackLng: 'en',
lng: lingua_attiva,
debug: false,
ns: ['common'],
defaultNS: 'common',
backend: {
loadPath: './i18n/{{lng}}/{{ns}}.json',
crossDomain: true,
parse: function (data) {
// queste 3 righe sotto mi fanno utilizzare il json che include anche la lingua.
// infatti, nel caso di un file per lingua, la lingua non andrebbe messa. Solo che ci sono delle estensioni
// come quella di PHP che la vogliono lo stesso. Per questo la lascio e la escludo.
try {
var json = JSON.parse(data); // --> { en: { ... } }
var m = Object.keys(json); // --> ['en']
return json[m[0]]; // --> { common: { ... } }
} catch (e) {
alert(e); // error in the above string (in this case, yes)!
}
},
},
},
function (err, t) {
// initialized and ready to go!
// Se in ingresso non avevo passato nessuna lingua, la imposto adesso con quella rilevata
if (lingua_attiva == undefined) {
lingua_attiva = i18nextInstance.language.substr(0, 2);
}
// Se la lingua non è tra quelle abilitate, forzo inglese
if (lingua_attiva != 'it' && lingua_attiva != 'en') {
lingua_attiva = 'en';
}
ConfiguraMainWebsite();
AggiornaTraduzioni();
}
);
// Configuro le opzioni per utilizzare jquery nelle traduzioni
jqueryI18next.init(i18nextInstance, $, {
tName: 't', // --> appends $.t = i18next.t
i18nName: 'i18n', // --> appends $.i18n = i18next
handleName: 'localize', // --> appends $(selector).localize(opts);
selectorAttr: 'data-i18n', // selector for translating elements
targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if diffrent then itself)
optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
useOptionsAttr: true, // see optionsAttr
parseDefaultValueFromContent: true, // parses default values from content ele.val or ele.text
});
You can create a new file with diffs only (this means that the keys are the same as in the common file), let's call it diffs and use i18next namespace fallback feature.
In a specific place you can use diffs namespace (which will load diffs.json file) and fallback to your common namespace for missing keys.
Since your config is already defined common as a defaultNS, all you need to do is just for the specific user change the namespace to diffs.
<div class="outer" data-i18n="diffs:key"></div>
// -----------------------------^
$(".outer").localize();
You can define the namespace for a specific region of translation
$(".outer").localize({ns: 'diffs'});
// this will call translation on the `.outer` div with a specific namespace without the need to attach it as I've showed before

How to extract values from Bing Speech API output

I am using the Bing Speech API (with Javascript - REST API) and as a result get something like this:
[{
"lexical":"gerson de laudos médicos por meio do reconhecimento automático",
"display":"gerson de laudos por meio do reconhecimento automático",
"inverseNormalization":null,
"maskedInverseNormalization":null,
"transcript":"gerson de laudos por meio do reconhecimento automático",
"confidence":0.7618318
}]
How do I get the result is just what is transcribed? For example, I would like to output only was the text: "gerson de laudos médicos por meio do reconhecimento automático"
You can use JSON.parse to get the results,
For ex : JSON.parse(results.d).transcript, here results.d is the resultant json data you got from Bing API & transcript
Hope that helps, let me know if you need further clarification.
I said these lines:
lexical: r.lexical,
display: r.name,
inverseNormalization: null,
maskedInverseNormalization: null,
Now to take [{"transcript":" and "}], I will use Javascript.

Read JSon string with Javascript and PHP

In a Javascript file i receive this JSon string into a hidden html string:
<input id="page_json_language_index" type="hidden" value="[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]">
from MySQL database in user language (this example is in French (fr) so, i need to access in Javascript to each "id" and each value of this 'id"
Example : for the first "id"
i need to obtain on separate variables for each ID and VALUE
var label = "label_accept_terms";
and other variable
var value = "En cliquant sur le bouton ci-dessous, vous accepter de respecter les "
so i have a problem to read and affected each ID with good label and value.
Thank you for your helping !
I must point out that you've made a mistake in your HTML. You should escape the quotes to avoid breaking attributes, for example, simply replace them with apostrophe:
<input id="page_json_language_index" type="hidden" value='[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]'>
JSON.parse is the best way to convert JSON string, but it's not surpported by old IE (e.g. IE6). You can use JSON2 to make it compatible, or just simply use eval().
Aware that abuse of eval() may lead to XSS (Cross Site Scripting) vulnerability. Make sure that the JSON you're about to parse is safe (doesn't include malicious Javascript).
Here's an example to read all id:
<input id="page_json_language_index" type="hidden" value='[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]'>
<textarea id="debug-console" cols="50" rows="20"></textarea>
<script type="text/javascript">
var arr = eval(document.getElementById("page_json_language_index").value),
output = document.getElementById("debug-console");
//output all id
for(var i=0; i<arr.length; i++)
output.value += [i, ": ", arr[i].id, "\n"].join("");
//show the first id
alert(arr[0].id);
</script>
Actually you can directly output JSON to Javascript.
To meet your needs, I think here's what you need.
<?php
...
$data = ...; //for example, from mysql query results
$language = "fr"; //you can replace it with it/en/zh...
...
?>
<input id="some_id"></input>
<script>
(function() {
var i18n = "<?php echo json_encode($data); ?>",
lang = "<?php echo $language; ?>", //language
data = eval(i18n); //you can also use JSON.parse/jQuery.parseJSON ...
for(var i=0; i<data.length; i++) {
document.getElementById(data[i].id).value = data[i][lang]; //a general way to read object's attribute in Javascript
}
})()
</script>
i need to obtain on separate variables for each ID and VALUE
This is not the way to go, you don't want to pollute your scope with a bunch of variables. What you have is a collection (array of objects). You can loop such collection and access the properties you need.
var input = document.getElementById('page_json_language_index');
var data = JSON.parse(input.value); // collection
the goal is to assign to each pair of (id, fr) value into a jquery
label
var label = function(lab) {
return '<label id="'+ lab.id +'">'+ lab.fr +'</label>';
};
var labels = data.map(label);
You can also make it a jQuery collection:
var $labels = $(labels.join(''));
Then you can append it to any container:
$labels.appendTo('body');

Send extra params to a view on backbone.js

I was trying the solutions that suggest in this questions but it don't work
How to pass parameters to a view
How can I pass a parameter into a Backbone.js view?
Backbone.js - passing arguments through constructors
I am trying to pass extra parameter to use in my template, I read that all extra params that I pass I can have access to them in this.options.varName but it dont work for me.
heres the controller code:
servicios : function(){
//Crea la colecion de tipos de servicios municipales
//Crea el modelo para dar de alta un nuevo reporte de servicio municipal
var reporteServicioSingle = new ReporteServicioSingle();
//Crea la vista para la pantalla de servicios municipales
var servicios_view = new Servicios({
model : reporteServicioSingle,
collection : this.reportes,
tipos : this.tipos
});
// Carga la vista renderisada y inicializa foundation
$("#app-content").html(servicios_view.render().el);
$(document).foundation();
},
And this is my view code:
render: function(){
console.log(this.options.tipos);
this.$el.html(Handlebars.templates.servicios(this.collection));
$(document).foundation();
return this;
},
but the chrome developers console, send me an error that options is not definided.
Uncaught TypeError: Cannot read property 'tipos' of undefined
Thank you and sorry for my bad english.
Assuming you're using Backbone 1.1, it no longer attaches the options argument to this.options automatically anymore, a shitty change (imho).
You'll need to extend the options parameter yourself in your initialization method:
initialize: function(options) {
this.options = _.omit(options, ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']);
}

Categories