eval specific part within a string Javascript - javascript

I have a following string
var popupValue = { "empID": "jQuery('#3566_textbox').val()","empName": "jQuery('#3567_textbox').val()"};
i just want the output to be:
var popupValue = { "empID": "1","empName": "ABC"};
i am failing to parse my string, can someone help me on that
code i have tried:
var popupValue = { "empID": "eval(\"jQuery('#3566_textbox').val()\")","empName": "eval(\"jQuery('#3567_textbox').val()\")"};
i am getting parse exception

You need to create an object and add the textbox values to it. WHat you are doing now is creating a string with the values jQuery('#3566_textbox').val() as part of that string, not as the actual textbox values.
<script>
var jsonObject = new Object();
jsonObject.empID = $('#3566_textbox').val();
jsonObject.empName = $('#3567_textbox').val();
var popupValue = JSON.stringify(jsonObject);
console.log(popupValue);
</script>

Related

How to access variables inside an array

So, I have been trying to solve this all of yesterday and today but cannot figure it out. I have the following returned in a variable called
var myRequest = req.body
console.log(myRequest)
Produces the following:
{
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
}
Now, I need to access the params key, and access the first param value so that whatever is returned in the first param value string is stored as username in a variable, and whatever is returned in param value string (the second one), is stored as a password.
So the final effect something like this:
var username = myRequest.methodcall.params.param...first value string
var password = myRequest.methodcall.params.param...second value string
However, I am really struggling to understand how to do this. Im guessing forEach loops would come in this, however I do not have experience with them so would appreciate some tips.
Also, when I try doing myRequest.methodcall, I keep getting undefined returned.
Any help will be greatly appreciated!
It sounds like your value is in JSON, parse it first and then you should presumably be able to get its values:
var myRequest = JSON.parse(req.body);
var userName = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];
What you have posted is JSON. you need to set it up like:
var myRequest = JSON.parse(req.body)
this will allow you to access the it like a normal js object.
Use . to access keys in object and [] to access index in array.
This code should work:
var username = myRequest.methodcall.params[0].param[0].value[0].string[0]
If you would like to use a loop at get the values test1,password, and so on. You can use a loop and access the param array:
var params = myRequest.methodcall.params[0].param;
params.forEach(function(item){
console.log(item.value[0].string[0]);
});
Fiddle
//var myRequest = JSON.parse(req.body) // if JSON
var myRequest = {
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
};
var params = myRequest.methodcall.params;
var uname, pwd;
for (var i = 0; i < params.length; i++) {
console.log("uname is " + params[i].param[0].value[0].string);
console.log("pwd is " + params[i].param[1].value[0].string)
}
if your response structure will be same then no need to go for loop or something, just directly access the username and password from response.
try this.
var username = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];
Did you debug your code?
I mean these code:
var username = myRequest.methodcall.params.param[0];
var password = myRequest.methodcall.params.param[1];

Razor inside javascript key value declaration?

Given the need to extract data from a viewdata into a javascript key/value object:
var stuff = {
something : [#someVar.Prop2, #someVar.Prop3, etc]
};
I want to make the key have the "name" of someVar.Prop1 so that:
var stuff = {
#someVar.Prop1 : [#someVar.Prop2, #someVar.Prop3, etc]
};
Yet when I use the form in the second code block above, I get a Expected identifier, string or number error at the colon:
#someVar.Prop1 : [#someVar.Prop2, etc]
---------------X (x marks the spot)
How do I need to format the razor code so that it knows what I'm trying to say?
You should definitely not be trying to build your JSON piece by piece in your Razor view. That can go wrong very easily.
To expand on #DLeh's answer, what you can do is build a dictionary of the values you want, serialize that into JSON right in your Razor view, and assign that to your variable as shown here:
#{
// Assume that someVar is provided from somewhere else;
// this is just for demonstration
var someVar = new { Prop1 = "My Prop", Prop2 = "Prop Value", Prop3 = 7 };
}
#{
var obj = new Dictionary<string, object>
{
{someVar.Prop1, new object[] { someVar.Prop2, someVar.Prop3 } }
};
}
<script>
var stuff = #Html.Raw(Json.Encode(obj));
</script>
Rendered output:
<script>
var stuff = {"My Prop":["Prop Value",7]};
</script>
You can surround razor expressions in quotes ' or " to have them output into a javascript block. If you need the type to be preserved properly, you can use methods like parseInt() or parseFloat() to do so.
Example:
var stuff = {
value1 : '#val1',
value2 : [ parseInt('#val2'), parseInt('#val3') ]
};
If you need to left side of the assignment to be variable, you will probably need to build a json string and then parse that into the object. Something like this, my quotes might be off.
var stuffJson = '{"#value1" : "#val1", "#value2" : "[ #val2, #val3 ]" }';
var stuff = JSON.parse(stuffJson);
If you're doing this a lot, you might want to consider using the Json() method in your controller to help you build these more easily. You could build a dictionary of key / value and have that output json:
public virtual ActionResult GetStuff()
{
string value1 = "key1",
value2 = "key2",
val1 = "str1",
val2 = "str2",
val3 = "str3";
var dict = new Dictionary<string, object>
{
{ value1, val1},
{ value2, new List<string> { val2, val3} },
};
return Json(dict, JsonRequestBehavior.AllowGet);
}
Output:
{"key1":"str1","key2":["str2","str3"]}
The answer is to ignore Visual Studio's complaint of the problem as the code runs and throws no error:
#country.CountryCode: ['#someVar.Prop1', '#someVar.Prop2', etc],

Get value from json string using fields

I have a json string. I want to get the values from that string using the field name. Please help me to get this. This is my json string format.
[
{
"FLD_ID": 1,
"FLD_DATE": "17-02-2014 04:57:19 PM"
"FLD_USER_NAME": "DAFEDA",
"FLD_USER_EMAIL": "test#gmail.com",
"FLD_USER_PASS": "test"
}
]
I'm not really sure what the question is but how about
// assuming str is your JSON string
var obj = JSON.parse(str); // parse the string into an object
var firstObj = obj[0]; // get the first (and only) object out of the array
var fld_id = firstObj.FLD_ID; // you can access properties by name like this
var fld_date = firstObj['FLD_DATE']; // or like this
your JSON was invalid. I fixed it for you.
[{"FLD_ID":1,"FLD_DATE":"17-02-2014 04:57:19 PM", "FLD_USER_NAME":"DAFEDA","FLD_USER_EMAIL":"test#gmail.com","FLD_USER_PASS":"test"}]
here's a working example of how to alert the FLD_ID
<script>
var json = [{"FLD_ID":1,"FLD_DATE":"17-02-2014 04:57:19 PM", "FLD_USER_NAME":"DAFEDA","FLD_USER_EMAIL":"test#gmail.com","FLD_USER_PASS":"test"}];
alert(json[0].FLD_ID);
</script>
By the way, this is an array with 1 JSON object, which is why you must reference the index, 0 in this case.

Parse json array using javascript

I have a json arry
var students = {"apResults":[{"offid":"267","item_name":"","offer_name":"fsdfsf","stlongitude":"77.5945627","stlatitude":"12.9715987"},
{"offid":"265","item_name":"","offer_name":"vess offer shops","stlongitude":"","stlatitude":""},
{"offid":"264","item_name":"","offer_name":"vess ofer shop","stlongitude":"","stlatitude":""},
{"offid":"263","item_name":"","offer_name":"ofer frm vess","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"262","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"261","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"260","item_name":"","offer_name":"offer1","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"259","item_name":"","offer_name":"offer","stlongitude":"77.5943760","stlatitude":"12.9716060"}]}
How i can parse this json arry using json.parse. I have tried this code
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults);
var offid = contact.offid;
alert(offid)
}
But its giving an error JSON.parse: unexpected character.Edited my question
That's not a json string, that's a regular javascript variable:
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults[i].offid);
alert(contact)
}
JSON parses strings, not objects/arrays.
why need parsing when you can access it like students.Maths[i].Name
students is not a JSON array, it's an actual array. You don't have to parse because it's not a string. So you can access directly to the data you need:
for(i=0;i<students.Maths.length;i++) {
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
You can't parse students because is not a JSON. It's simple object.
However this will work:
var students = JSON.stringify(students); // if you want to send data
students = JSON.parse(students); // after receiving make a object from it
//use like any object
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
Of course it doesn't make sense to write it that way unless you send students data to other site or program.
Edit:
You don't need JSON in this code at all. But if you want to test JSON.parse() do it this way:
var students = { ... } // your data
var students = JSON.stringify(students); // students is `object`, make it `string`
students = JSON.parse(students); // now you can parse it, `students` is object again
for(i=0;i<students.apResults.length;i++) {
var contact = students.apResults; // no JSON
var offid = contact.offid;
alert(offid)
}
That should work.
What you have is a javascript object. So, you won't need the JSON.parse
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i]);
var fullname = contact.Name;
alert(fullname)
}
this should be ok
The idea of JSON is for the exchange of objects represented as a structured string (in a nutshell). What you've got there is simply an object. It's unnecessary (and impossible) to parse and object that isn't JSON into a javascript object; what you have is the outcome of what you would expect from a parsed JSON string.

what is the preg match to extract this values using js

How to retrieve the value 100003119917070 and XgXELcliKMkSCcS from below document using preg match:
<script>
window.Env = window.Env || {};
(function(v) {
for (var k in v) { window.Env[k] = v[k]; }
})({
"user": "100003119917070",
"locale": "en_US",
"method": "GET",
"ps_limit": 5,
"ps_ratio": 4,
"svn_rev": 479734,
"static_base": "https:\/\/s-static.ak.facebook.com\/",
"www_base": "http:\/\/www.facebook.com\/",
"rep_lag": 2,
"post_form_id": "6cea66d4118fac268304a538a5004ed7",
"fb_dtsg": "AQAcBeoe",
"ajaxpipe_token": "AXgXELcliKMkSCcS",
"lhsh": "8AQGGa7eN",
"tracking_domain": "https:\/\/pixel.facebook.com",
"retry_ajax_on_network_error": "1",
"ajaxpipe_enabled": "1"
});
</script>
<script>
CavalryLogger=false;
window._incorporate_fragment = true;
window._script_path = "\/home.php";
window._EagleEyeSeed="Se1E";
</script>
Just access window.Env.user and window.env.ajax_token?
You've put(copy) the object into the window.Env, so you can run this code:
console.log(window.Env.user, window.Env.ajaxpipe_token)
and it will print values which you want on console.
Also, you can use window.Env['user'] to reference the value 100003119917070.
if use preg,
var preg_user= /"user":\s?"([0-9]+)/;
var preg_token = /"ajaxpipe_token":\s?"([\d\w]+)/;
and you can get value by:
var user = str.match(preg_user);
var token = str.match(preg_token);
May this can help you.
In the specific example given ajaxpipe_token does not contain values other than text and numbers, but, if your value can contain other values (like it can in facebook), change your match group to look for non-quotes, then terminate with the quotes. This is the full code for extracting the values from the document.
scriptxpath ='//script[contains(.,"ajaxpipe_token")]';
scriptrslt = document.evaluate(scriptxpath,document,null,XPathResult.ANY_TYPE,null);
scriptobj = scriptrslt.iterateNext()
scriptiHTML = script.innerHTML;
user_search = scriptiHTML.match(/"user":\s?"([0-9]+)"/);
ajaxpipe_token_search = script_iHTML.match(/"ajaxpipe_token":\s?"([^"]+)"/)
user = user_search[1];
ajaxpipe_token = ajaxpipe_token_search[1];

Categories

Resources