Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable in JSON path

I would like to make the path to data contained in JSON variable. The code I have now looks like this:

function writeDB(block)
{
  $.getJSON('js/data.js', function(data) {

    if (block == "path1") { var adr = data.test.path1.db; };
    if (block == "path2") { var adr = data.test.path2.db; };
    if (block == "path3") { var adr = data.test.path3.db; };

    var datastring="";
    $.each(adr, function(i, field){
      temp = encodeURIComponent($("#writeDB_"+block+" [name="+adr[i].abc+"]").val());
      datastring += adr[i].abc+"="+temp+"&";
    });

  });

}

The "if" parts I would like to simplify and make it variable, by using the variable 'block' directly into the "adr" path, something like this

var adr = "data.test."+block+".db";

But a string won't work, so its useless. Someone knows how I can fix that?

like image 525
Maarten Avatar asked Mar 14 '12 13:03

Maarten


People also ask

What is @jsonpath?

JSONPath is a query language for JSON with features similar to XPath for XML. JSONPath is used for selecting and extracting a sub-section from the JSON document. 1. JSONPath Dependencies

How do I access a profile from a JSON file?

If you want to access data from the profile object or data from the User Profile created with the Profiles API, use a full JSONPath expression such as $.profile.someProp. IE if you wanted to access the email, you could use the expression $.profile.email.

What is the syntax for the dollar sign in jsonpath?

The dollar sign is followed by a sequence of child elements, which are separated via dot (code) notation or via the square brackets (code). The important JSONPath syntax rules are:

What is the variableid in a VS Code project?

The variableID refers to entries in the inputs section of launch.json and tasks.json, where additional configuration attributes are specified. The following example shows the overall structure of a tasks.json that makes use of input variables: Currently VS Code supports three types of input variables:


2 Answers

You want to use square bracket notation:

var adr = data.test[block].db;
like image 129
Daniel A. White Avatar answered Nov 10 '22 00:11

Daniel A. White


if (typeof(data.test[block]) != "undefined")
    var adr = data.test[block].db;
....
like image 31
Vytautas Avatar answered Nov 09 '22 23:11

Vytautas