I am writing a function that takes a string, splits it, and the uses json[key][key2][key3] formatting. The problem is n is potentially infinite (not literally but needs to written that way)
function getJsonValue(json,string) {
var vals = string.split(".");
var x = vals.length;
var string = '';
while (x != 0) {
string += "['"+vals[(vals.length-x)]+"']"
x--
}
return string;
}
That will produce, for example: "['condition']['item']['condition']['temp']"
I need to extract a value from that by attaching it to a json object, like
json"['condition']['item']['condition']['temp']"
But I don't know how or if that is even possible.
Edit:
The problem is I need any value from a config file to be passed in and then parsed from a returning function. I.e. User knows the value will be condition.item.condition.temp for this specific query. I am trying to write one function that covers everything and pass in config values for what I know to be the output. So, on one query, I might want the condition.item.condition.temp value and on another I might want condition.wind.chill .
I'm not sure if I understand 100% what you're trying to do, but if you're receiving a JS object json and a string in the format field1.field2.field3 and trying to get the value of json.field1.field2.field3 then you can do something like this:
function getJsonValue(json,string) {
var vals = string.split(".");
for (var i = 0; i < vals.length; i++) json = json[vals[i]];
return json;
}
It would work like this for a given object:
var obj = { field1: { field2: { field3: "Hello!" } } };
var res = getJsonValue(obj, "field1.field2.field3");
console.log(res); // prints Hello
See lodash get
_.get(json, 'key1.key2.key3')
you can build the "path" from your current code and ask lodahs to get the value out for you.
What about doing an eval?
var json = {
'one': {
'two': {
'three': {
'four': 4
}
}
}
};
alert(eval("json['one']['two']['three']['four']"))
Related
In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .
After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe
I have a fairly large javascript/html application that updates frequently and receives a lot of data. It's running very quickly and smoothly but I need to now introduce a function that will have to process any incoming data for special chars, and I fear it will be a lot of extra processing time (and jsperf is kinda dead at the moment).
I will make a request to get a .json file via AJAX and then simply use the data as is. But now I will need to look out for strings with #2C (hex comma) because all of the incoming data is comma-separated values.
in File.json
{
names: "Bob, Billy",
likes : "meat,potatoes
}
Now I need
{
names: "Bob, Billy",
likes : "meat#2Cbeear#2Cwine,potatoes
}
where #2C (hex for comma) is a comma within the string.
I have this code which works fine
var str = "a,b,c#2Cd";
var arr = str.split(',');
function escapeCommas(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf("#2C") !== -1) {
var s = arr[i].replace("#2C", ',');
arr[i] = s;
}
}
return arr;
}
console.log(escapeCommas(arr));
http://jsfiddle.net/5hogf5me/1/
I have a lot of functions that process the JSON data often as
var name = str.split(',')[i];
I am wondering how I could extend or re-write .split to automatically replace #2C with a comma.
Thanks for any advice.
Edit: I think this is better:
var j = {
names: "Bob, Billy",
likes : "meat#2Cpotatoes"
};
var result = j.likes.replace(/#2C/g, ',');
// j.likes.replace(/#2C/ig, ','); - if you want case insensitive
// and simply reverse parameters if you want
console.log(result);
This was my initial approach:
var j = {
names: "Bob, Billy",
likes : "meat,potatoes"
}
var result = j.likes.split(",").join("#2C")
console.log(result);
// meat#2Cpotatoes
Or if you have it the reverse:
var j = {
names: "Bob, Billy",
likes : "meat#2Cpotatoes"
}
var result = j.likes.split("#2C").join(",")
console.log(result);
// meat,potatoes
[Updated to reflect feedback] - try at http://jsfiddle.net
var str = 'a,b,c#2Cd,e#2Cf#2Cg';
alert(str.split(',').join('|')); // Original
String.prototype.native_split = String.prototype.split;
String.prototype.split = function (separator, limit) {
if ((separator===',')&&(!limit)) return this.replace(/,/g,'\0').replace(/#2C/gi,',').native_split('\0');
return this.native_split(separator, limit);
}
alert(str.split(',').join('|')); // Enhanced to un-escape "#2C" and "#2c"
String.prototype.split = String.prototype.native_split;
alert(str.split(',').join('|')); // Original restored
Couple minor tangential notes about your function "escapeCommas": this function is really doing a logical "un-escape" and so the function name might be reconsidered. Also, unless it is your intention to only replace the first occurence of "#2C" in each item then you should use the "g" (global) flag, otherwise an item "c#2Cd#2Cde" would come out "c,d#2Ce".
This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}
I have code that calls a WCF service and returns a JSON string to the client. Below is the javascript function I am trying to use to parse the JSON but can not figure out how to traverse it.
Here is the function
loadDropDown: function(result, ddl, defaultItem) {
var _data = result.get_object();
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;
}
Here is the JSON
{
"d": "[{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Lexus\",\"Value\":\"Lexus\"},{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Acura\",\"Value\":\"Acura\"}]"
}
any suggestions on why this is not working? Note: I am not using jquery in the solution.
You shouldn't be generating that json. Instead, you should be outputting
{
"d": [{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Lexus","Value":"Lexus"},{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Acura","Value":"Acura"}]
}
(quotes removed from "d" value)
There's no reason to convert json to a string before putting it in a json object! Just put the json straight in.
You should be able to just eval() the object (or use JSON parsing from Crockford) and access your properties in regular object notation. You may need to unescape your identifiers first, though.
You need to do eval(_data) before you use it as a javascript array.
for ex:
var _rawdata = result.get_object();
var _data = eval(_rawdata);
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;