ProMike360 ProMike360 -4 years ago 118
JSON Question

jQuery search in an object using a string

I want to search in a object using a string.



"nl": {
"header-WelcomeText":"Welkom op de website",
"en": {
"header-WelcomeText":"Welcome on the website",


var output;
$.get("file.json", function(response){
output = response; //This is now a object in javascript

This all works, here what i want:

//The jQuery code
$('span .lang').text($(this).attr("data-lang"));

//The HTML code
<span class="lang" data-lang="header-Sub1"></span>

I know this will not work, but I know there will be a way to achief this.

Answer Source

To make this work there's a few changes you need to make.

  • when accessing the key of an object through a variable you need to use bracket notation.
  • to reference the element through the this keyword you need to run your code within it's scope. To do that you can pass a function to the text() method which returns the value you need from the object.
  • the .lang class is directly on the span, so you shouldn't have the space in your selector.

With all that in mind, this should work for you:

var output = {
  "nl": {
    "lang": "Nederlands",
    "header-WelcomeText": "Welkom op de website",
    "header-Sub1": "Hoofdpaneel"
  "en": {
    "lang": "English",
    "header-WelcomeText": "Welcome on the website",
    "header-Sub1": "Dashboard"

$('span.lang').text(function() {
<script src=""></script>
<span class="lang" data-lang="header-Sub1"></span>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download