Javascript/jQuery search json for a string then run a function - javascript

I need to run a function matchFound() if a string is found in an external json file.
This is what I have so far:
function init(){
$.ajax({
type: "GET",
url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&callback=?&q=http://www.domain.com/feed.rss",
dataType: "json",
success: parseData
});
}
function parseData(data){
var string_to_find = "Hello World!";
// look into the data and match the string
}
function matchFound(str, string_to_find){
alert('Match found in string - '+ str +'\r\n While looking for the string- '+ string_to_find);
return true;
}
function matchNotFound(){
alert('No Match found!');
}
But I don't know how to parse the Json data and search for a string.
I have this for XML (thanks #Ohgodwhy) but not sure how to translate for json
function parseXml(xml){
var string_to_find = "Hello World!";
$(xml).find('title').each(function(){
var str = $(this).text();
if(str.indexOf(string_to_find) > -1){
if(matchFound(str, string_to_find)){
return false;
}
}
});
}
The search location within the variables is: responceData > feed > entries > [0] or 1 or [2] etc > contentSnippet
I only need to match the first 10 characters.
If a match is found then run the funciton matchFound() or if not found run the function matchNotFound()
Any help with this is very much appreciated.
C

you have to iterate json recursively and then search for the string
function parseData(data){
var string_to_find = "Hello World!";
var is_found = iterate(data , string_to_find);
if(is_found === true){
matchFound(JSON.stringify(data), string_to_find);
}else{
matchNotFound(string_to_find);
}
// look into the data and match the string
}
function iterate(obj , string_to_find) {
for(var key in obj) { // iterate, `key` is the property key
var elem = obj[key]; // `obj[key]` is the value
console.log(elem, string_to_find);
if(typeof(elem)=="string" && elem.indexOf(string_to_find)!==-1) {
return true;
}
if(typeof elem === "object") { // is an object (plain object or array),
// so contains children
return iterate(elem , string_to_find); // call recursively
}
}
}

Related

Convert nested form fields to JSON in Jquery

Trying to do POST of Form object as JSON from front end javacsript/jquery to Spring MVC backend.
Form data has a string array and other string field, looks like below
...
var cityList = [];
citylist.push("SF");
citylist.push("LA");
document.forms["myForm"]["dstCities"].value = cityList;
document.forms["myForm"]["dstState"].value = "CA";
...
Below is my code for converting to JSON,
function convertFormToJSON(){
var jsonObject = {};
var array = $("myForm").serializeArray();
$.each(array, function() {
if (jsonObject[this.name] !== undefined) {
jsonObject[this.name].push(this.value || '');
} else {
jsonObject[this.name] = this.value || '';
}
});
jsonObject = JSON.stringify(jsonObject);
console.log("json: " + jsonObject);
return jsonObject;
};
POST call:
$.ajax({
url: "xxx",
type: "POST",
data: convertFormToJSON(),
contentType: "application/json",
dataType: 'json',
...
});
Json output:
{"dstCities":"SF,LA", "dstState":"CA"}
But I need it to look like
[{"dstCities": ["SF", "LA"], "dstState":"CA"}]
You are passing an array as value to :
document.forms["myForm"]["dstCities"].value = cityList;
but the browser is using toString() on it and it ends up as joined string "SF,LA"
If the intent is to pass it as string array can do:
document.forms["myForm"]["dstCities"].value = JSON.stringify(cityList);
No changes would be needed in convertFormToJSON this way.
If the cities need to be displayed as comma separated values then change
if (jsonObject[this.name] !== undefined) {
jsonObject[this.name].push(this.value || '');
} else {
var value = this.value;
if (this.name === 'dstCities') {
value = value.split(',');
}
jsonObject[this.name] = value || '';
}

Javascript : How to concat string to object?

I have following code where i combine some variables to create path to the another existing object and his attribute.
Problem is that i alway get only string, so i would like to "convert" it into the object.
// SET CUSTOM CONTENT FOR COLUMN IF CONTACT ATTR IS EXISTS
if(value.concatByFields != null) {
preparedGridColumnItem.template = function (responseData) {
var nameForConcat;
var fieldName;
var objectName;
var pathToReturn;
$.each(value.concatByFields, function( index, concatField ) {
nameForConcat = null;
fieldName = null;
objectName = null;
objectName = value.field;
fieldName = concatField.fieldName;
console.log("FIELD NAME IS");
console.log(JSON.stringify(fieldName));
console.log("OBJECT NAME IS");
console.log(objectName);
nameForConcat = objectName+"."+fieldName;
console.log("CONCATED NAME IS");
console.log(nameForConcat);
console.log("OBJECT ADDRESS IS FOLLOWING");
console.log("responseData."+nameForConcat);
pathToReturn = "responseData."+nameForConcat;
});
//TODO : IS ALWAYS RETURNED AS STRING
return pathToReturn;
};
}
Returned value should be value of another and global existing json object. But now is it always string.
It means:
responseData.SomeObject.surname
How can i solve it please?
Many thanks for any help.
if(value.concatByFields != null) {
preparedGridColumnItem.template = function (responseData) {
var fieldName;
var objectName;
var pathToReturn;
$.each(value.concatByFields, function( index, concatField ) {
objectName = value.field;
fieldName = concatField.fieldName;
pathToReturn = responseData[objectName][fieldName];
});
//TODO : IS ALWAYS RETURNED AS STRING
return pathToReturn;
};
}

Convert javascript object or array to json for ajax data

So I'm creating an array with element information. I loop through all elements and save the index. For some reason I cannot convert this array to a json object!
This is my array loop:
var display = Array();
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
I try to turn it into a JSON object by:
data = JSON.stringify(display);
It doesn't seem to send the proper JSON format!
If I hand code it like this, it works and sends information:
data = {"0":"none","1":"block","2":"none","3":"block","4":"block","5":"block","6":"block","7":"block","8":"block","9":"block","10":"block","11":"block","12":"block","13":"block","14":"block","15":"block","16":"block","17":"block","18":"block","19":"block"};
When I do an alert on the JSON.stringify object it looks the same as the hand coded one. But it doesn't work.
I'm going crazy trying to solve this! What am I missing here? What's the best way to send this information to get the hand coded format?
I am using this ajax method to send data:
$.ajax({
dataType: "json",
data:data,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
Using GET method because I'm displaying information (not updating or inserting). Only sending display info to my php file.
END SOLUTION
var display = {};
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
$.ajax({
dataType: "json",
data: display,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
}
To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:
// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
return oldJSONStringify(convArrToObj(input));
};
})();
And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)
Edit:
Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
jsFiddle with example here
js Performance test here, via jsPerf

How to use a different json parser for jQuery.ajax?

I have json data with "tagged" values (from a jsonp source):
{"foo": "#duration:8542"}
which I can parse on-the-fly by passing a function as the second argument to JSON.parse:
dk.json = {
parse: function (s) {
return JSON.parse(s, function (key, val) {
if (typeof val === 'string' && val[0] === '#') {
var colonpos = val.indexOf(':');
if (colonpos > 1) {
var tag = val.slice(0, colonpos + 1);
switch (tag) {
case dk.Date.tag: return dk.Date.create(val);
case dk.Duration.tag: return dk.Duration.create(val);
}
}
}
return val;
});
},
//...
};
but how can I plug this parsing function into jQuery.ajax()? Something more sensible than:
success: function (data) {
data = dk.json.parse(JSON.stringify(data));
...
dataFilter, and especially converters looked promising:
$.ajax({
dataType: 'jsonp',
converters: {
'text json': dk.json.parse
},
// ...
});
but that doesn't get called at all (dataFilter gets called, but with the data parameter set to undefined).
Where am I going wrong?
[Edit:]
I know I can write a traversal function that walks the JSON object returned by jQuery, eg:
function untag(val) {
if (typeof val === 'string' && val[0] === '#') {
var colonpos = val.indexOf(':');
if (colonpos > 1) {
var tag = val.slice(0, colonpos + 1);
switch (tag) {
case dk.Date.tag: return dk.Date.create(val);
case dk.Duration.tag: return dk.Duration.create(val);
}
}
}
return val;
}
var untag_json = function (jsonobj) {
var _traverse = function _traverse(obj, result) {
var value;
for (var attr in obj) {
value = obj[attr];
if (value && typeof value === 'object') {
result[attr] = _traverse(value, {});
} else {
result[attr] = untag(value);
}
}
return result;
};
return _traverse(jsonobj, {});
};
and then call it in the success handler:
success: function (data) {
data = untag_json(data);
...
but that seems like a lot of unnecessary work.. Is there no way to use the converters parameter to $.ajax to get access to the unparsed (i.e. text) json source?
There actually isn't any JSON parsing in a JSONP request (src), which can seem counter intuitive. What is happening is the string that is returning from the JSONP endpoint is evaluated as JavaScript (with a reference to a function that is defined (or added in dynamically) in the DOM making the JSONP request like this:
_callback({'foo':'#duration:8524'});
If you wanted to use your function you would need to make the endpoint return a String like this:
_callback("{'foo':'#duration:8524'}");
then in the JSONP callback you could call JSON.parse(). JSON parse is a rather safe way to process JSON so if this was easier to reason about then it would be a fine approach.
Hi you need to set this header application/json in the response from server side then you can simply set dataType:json or dataType:jsonp then you will not need to stringify or parse the json. You then just get objects, properties or arrays from json.
For example : in php we use
$json_string = "{"foo": "#duration:8542"}";
$json = json_decode($json_string);
$foo = $json->foo;
echo $foo;//prints #duration:8542
In jquery you can do this:
sucess:function(response) {
var foo = response.foo;
console.log(foo);
}
Hope this helps

Is there a Jquery function that can take a #ref id value from a parsed JSON string and point me to the referenced object?

I have been looking for an answer to this all afternoon and i cant seem to find the best way to accomplish what i need to.
My JSON string (returned from a web service) has circular references in it (#ref) which point to $id in the string. Now i know that if use jquery parseJSON it creates the javascript object and i can access properties a la myObject.MyPropertyName. However, when i get to a #ref, i am unsure how to get the object that ID points to (which i assume is already created as a result of the de-serialization...
Should i be iterating though the object and all its child objects until i find it, or is there an easier way?
$.ajax({
type: "POST",
url: "/Task.asmx/GetTask",
data: "{'id':'" + '27' + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
_Data = $.parseJSON(msg.d ? msg.d : msg);
_this.Company = _Data[0].t_Program.t_Company;
_this.Program = _Data[0].t_Program;
_this.Task = _Data[0];
},
complete: function () {
}
});
The area in question is _Data[0].t_Program because it does not return an object but rather returns
_Data[0].t_Program
{...}
$ref: "12"
I dont exactly know the best way to get the object with $id "12". Based on the posts below it seems i should loop through the existing object, but i was hoping there was a jquery function that did that...
Many Thanks!
No, jQuery is not natively capable of resolving circular references in objects converted from JSON.
The only library for that which I know is Dojo's dojox.json.ref module.
But, your server application serializes that JSON somehow. Don't tell me that the solution it uses does not offer a deserialisation algorithm!
As my friend Alan, the author of the Xerox Courier (RPC over the net) library, used to say to me, "there are no pointers on the wire."
In other words, it is impossible for a JSON representation of a data structure to be circular. (But a circular structure can be flattened into a non-circular JSON structure.) As the JSON site says:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
No pointers!
So the entire JSON will have been turned into Javascript Objects and/or Arrays after the jQuery parseJSON operation completes.
If the original stucture's ref_id values were used as the property names in the JSON / Javascript object, then they'll all be there.
The real issue is that you need to understand how your server serialized its data structure into the JSON data structure. Look in your server-side code to determine that.
Then use Javascript to de-serialize the JSON structure back into the best Javascript structure to fit your needs.
Re: Should i be iterating though the object and all its child objects until i find it, or is there an easier way?
The easier way would be to go through the Javascript structure once, and build up an additional "indexing" object whose properties are the #ref_id and the values are the original structure/value.
Sample:
var jsonCyclicReferenceFixed = JsonRecursive.parse(jsonWithRefAndId);
(function(){
function type(value){
var t = typeof(value);
if( t == "object" && value instanceof Array) {
return "array";
}
if( t == "object" && value && "$id" in value && "$values" in value) {
return "array";
}
return t;
}
function TypeConverterFactory(){
var converters = {};
var defaultConverter = {
fromJson: function(value){ return value; },
toJson: function(value){ return value; },
};
this.create = function(type){
var converter = converters[type];
if(!converter) return defaultConverter;
return converter;
};
this.register = function(type, converter){
converters[type] = converter;
converter.valueConverter = this.valueConverter;
};
}
function ObjectConverter(){
this.fromJson = function(obj){
if( obj == null ) return null;
if( "$ref" in obj ){
var reference = this.dictionary[obj.$ref];
return reference;
}
if("$id" in obj){
this.dictionary[obj.$id] = obj;
delete obj.$id;
}
for(var prop in obj){
obj[prop] = this.valueConverter.convertFromJson(obj[prop]);
}
return obj;
}
this.toJson = function(obj){
var id = 0;
if(~(id = this.dictionary.indexOf(obj))){
return { "$ref" : (id + 1).toString() };
}
var convertedObj = { "$id" : this.dictionary.push(obj).toString() };
for(var prop in obj){
convertedObj[prop] = this.valueConverter.convertToJson(obj[prop]);
}
return convertedObj;
}
}
function ArrayConverter(){
var self = this;
this.fromJson = function(arr){
if( arr == null ) return null;
if("$id" in arr){
var values = arr.$values.map(function(item){
return self.valueConverter.convertFromJson(item);
});
this.dictionary[arr.$id] = values;
delete arr.$id;
return values;
}
return arr;
}
this.toJson = function(arr){
var id = 0;
if(~(id = this.dictionary.indexOf(arr))){
return { "$ref" : (id + 1).toString() };
}
var convertedObj = { "$id" : this.dictionary.push(arr).toString() };
convertedObj.$values = arr.map(function(arrItem){
return self.valueConverter.convertToJson(arrItem);
});
return convertedObj;
}
}
function ValueConverter(){
this.typeConverterFactory = new TypeConverterFactory();
this.typeConverterFactory.valueConverter = this;
this.typeConverterFactory.register("array", new ArrayConverter);
this.typeConverterFactory.register("object", new ObjectConverter);
this.dictionary = {};
this.convertToJson = function(valor){
var converter = this.typeConverterFactory.create(type(valor));
converter.dictionary = this.dictionary;
return converter.toJson(valor);
}
this.convertFromJson = function(valor){
var converter = this.typeConverterFactory.create(type(valor));
converter.dictionary = this.dictionary;
return converter.fromJson(valor);
}
}
function JsonRecursive(){
this.valueConverter = new ValueConverter();
}
JsonRecursive.prototype.convert = function(obj){
this.valueConverter.dictionary = [];
var converted = this.valueConverter.convertToJson(obj);
return converted;
}
JsonRecursive.prototype.parse = function(string){
this.valueConverter.dictionary = {};
var referenced = JSON.parse(string);
return this.valueConverter.convertFromJson(referenced);
}
JsonRecursive.prototype.stringify = function(obj){
var converted = this.convert(obj);
var params = [].slice.call(arguments, 1);
return JSON.stringify.apply(JSON, [converted].concat(params));
}
if(window){
if( window.define ){
//to AMD (require.js)
window.define(function(){
return new JsonRecursive();
});
}else{
//basic exposition
window.jsonRecursive = new JsonRecursive();
}
return;
}
if(global){
// export to node.js
module.exports = new JsonRecursive();
}
}());
Sample:
// a object recursive
// var parent = {};
// var child = {};
// parent.child = child;
// child.parent = parent;
//
//results in this recursive json
var json = '{"$id":"0","name":"Parent","child":{"$id":"1","name":"Child","parent":{"$ref":"0"}}}'
//Parsing a Recursive Json to Object with references
var obj = jsonRecursive.parse(json);
// to see results try console.log( obj );
alert(obj.name);
alert(obj.child.name);

Categories

Resources