Extract subset from json in javascript - javascript

I would like to substract json entries from the main JSON bulk data, based on an input, in JavaScript. Each entry in the main JSON data has it's own unique ID, but the filter should be based on the text identifier rather than the ID. I would like to retrieve for example all entries that contain the word burg (Burg, BURG, bUrg, etc.) or any other given variety. This should of course also work with other search terms. I do not possess the JavaScript skills to do this.
In the data given below this should return 3 results. Obviously, the result should be the exact same JSON format.
Example JSON:
{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}

Do not use JavaScript for this. Use SQL and its LIKE operator instead.
But if you insist on using JavaScript for this…
Just like HTML, regular expressions cannot fully parse JSON because of serialization.
Filtering after JSON.parse is quite easy however; you can use the Array.prototype.filter() method:
var s = '{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}';
var input = "burg";
var o = JSON.parse(s);
o.features = o.features.filter(e => RegExp(input, 'i').test(e.text));
console.log(JSON.stringify(o));

Related

Counting a particular word in a string using Zapier code

I use Zapier to automate many of our business functions, which is great, but I got stuck trying to count the number of arrays or, if you like, a particular word pattern that comes from a string. I can tidy up the string with Zapier formatter, but cannot figure out how to carry out a count.
Here is an example of a tidied string where " have been removed:
[{Name:Jon,Surname:Smith},{Name:David,Surname:Michael},{Name:Sam,Surname:Fields},{Name:Katy,Surname:Milnes}]
In this instance I would want the count on say "Name" to return 4.
I have looked at different code examples for counting words but cannot execute them correctly in the code action of Zapier. This is probably really straight forward but I do not come from a coding background so a simple Java (or Python) script to drop into the Zapier code action or some pointers on how to solve this would be greatly appreciated.
Thanks
What are you really trying to achieve by trying to count the word?
Do you just want to know the number of objects the array contains? If that is the case something like this would work. Assuming that the array is in your inputData for the code step.
var data = JSON.stringify([{'Name':'Jon', 'Surname':'Smith'},{'Name':'David','Surname':'Michael'},{'Name':'Sam','Surname':'Fields'},{'Name':'Katy','Surname':'Milnes'}]);
var inputData = {objArr: data};
// Do not insert the above lines in your code step.
// Set the objArr to your array in the inputData step.
var parsedObjArr = JSON.parse(inputData.objArr);
// Skip the above step if the array is not in the inputData object.
var arrLen = parsedObjArr.length
console.log('Array Length: ', arrLen);
// The line below outputs data from the code step.
output = {arrLen}
Also note, you do not need to remove the quotes from the JSON string.
If the array is not in the inputData of the code step, you can just directly use the length method on the array.
Well in Python you can convert the json string into dictionary with key as the name. Length of dictionary is what you are looking for. Here is the example:
import json
from collections import defaultdict
d=defaultdict(list)
x=json.dumps([{'Name':'Jon', 'Surname':'Smith'},{'Name':'David','Surname':'Michael'},{'Name':'Sam','Surname':'Fields'},{'Name':'Katy','Surname':'Milnes'}])
json_string=json.loads(x)
for obj in json_string:
if(obj['Name'] in d):
d[obj['Name']].append([obj['Name']+' '+obj['Surname']])
else:
d[obj['Name']]=[obj['Name']+' '+obj['Surname']]
print(len(d))

ionic 2 get data from malformed json

is there anyway i can get this malformed json format which is odd i have no control over this json manually so i need to get this data and manipulate it with rxjs observable from http get
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
I tried with your JSON in the console and this seems to work. In the map function I've used you can probably implement more generic replacement methods to alter the strings, but it works for this example.
function fixBadJSON(response){
let badJSON = JSON.stringify(response); // added this edit in case you don't know how to get the response to a string
let arr = badJSON.split('}\n'); // Looks like the JSON elements are split by linefeeds preceded by closing bracket, make into arr length of 3
let fixedArr = arr.map((item)=>{ // map the array to another, replace the comma at the end of the avatarImage key. elements in array should be proper JSON
if(item[item.length] != '}') item += '}'; //put the brackets back at thend of the string if they got taken out in the split, probably a better way to handle this logic with regex etc
return item.replace('jpg",','jpg"')
});
let parsedJSON = JSON.parse(JSON.stringify(fixedArr));
return parsedJSON
}
Take the JSON data you've posted up there and copy it to a variable as a string and test the function, it will return a properly formatted array of JSON data.
Call that when you get a response from your service to transform the data. As far as the observable chains and any async issues you might be seeing those are separate things. This function is just designed to convert your malformed JSON.

JSON decode list of lists in Django Python

I have a list of lists (e.g. [[1,2],[3,4]]) passed from a Django view to a javascript variable and submitted with jQuery. I need to parse that variable to pull indices. The basic process is:
Add as context variable (python):
resultMsgList.append(msg)
resultMsgListJson=json.dumps(resultMsgList)
resultDict['resultMsgListJson']= resultMsgListJson
Javascript:
var resultMsgList = {{resultMsgListJson}};
var data = {'resultMsgList':resultMsgList};
$.post(URL, data, function(result){
});
Google Console gives me:
Javascript:
var resultMsgList = [["View \"S03_2005_LUZ_140814_105049_with_geom\" was successfully created!", "luz_mapfile_scen_tdm_140814_105049", "S03_2005_LUZ_140814_105049_with_geom", "C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map", [25, 50, 498.26708421479, 131137.057816715]]];
I copied this result to a validator, which states it is correct JSON.
The post gives me:
resultMsgList[0][]:View "S03_2005_LUZ_140814_105049_with_geom" was successfully created!
resultMsgList[0][]:luz_mapfile_scen_tdm_140814_105049
resultMsgList[0][]:S03_2005_LUZ_140814_105049_with_geom
resultMsgList[0][]:C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map
resultMsgList[0][4][]:25
resultMsgList[0][4][]:50
resultMsgList[0][4][]:498.26708421479
resultMsgList[0][4][]:131137.057816715
I need to get elements from this list. I currently have (python):
resultMsgListContext = request.POST.get('resultMsgListJson','')
resultMsgListContext = json.loads(resultMsgListContext)
oldMapfileName=resultMsgListContext[0][2] (+ a number of similar statements)
According to this post I then need to decode the variable in python with json.loads(), but it says there is no JSON object to be decoded. Based on the examples in the Python docs, I'm not sure why this doesn't work.
I believe the problem is that it is viewing the entire resultMsgList as a string, substantiated by the fact that there is a u' xxxxx ' in the result. That's why it is saying index out of range because you're trying to access a 2D array when it is still a string. You have to convert it to an array of strings by using json.loads.
In javascript, try passing
var data = {'resultMsgListJson':resultMsgList};
instead of
var data = {'resultMsgListJson': resultMsgListJson};
resultMsgListJson isn't a javascript variable that's defined at that point, it might be getting evaluated to undefined.
In general, in python, print the contents of resultMsgListContext before trying to do json.loads on it so you can see exactly what you're trying to parse.

Retrieve JSON Array element value

My web service returned a JSON Array (ie. [{"key":"value"}, {"key":"value2"}]). In the array there are two items as you can see, which are separated with comma. I want to know how can I access the second item, and get the value of "key" for the second item.
I've tried:
var a = msg.d[1].key
With no success of course.
This is the returned string:
"[{"Code":"000000","Name":"Black","Id":9},{"Code":"BF2C2C","Name":"Red","Id":11}]"
The string was extracted using FireBug after watching the msg.d.
Need your help in solving this.
msg[1].key
Assuming that the name of that array is msg. I'm not sure what you are using .d for.
If msg.d is a string representing an array, use JSON.parse.
JSON.parse(msg.d)[1].key
You can replace key with the key you are wanting, e.g. Code, Name, Id, etc.
This works as expected for me.
var msg = [{"key":"value"}, {"key":"value2"}];
var a = msg[1].key;
What is msg in the example above? Need more info to help.
If msg.d is a string then you have to eval (uggh) or parse it before applying the array subscript.

JSON conversion in javascript

I'm trying to stringify a multi-array variable into a JSON string in Javascript. The
//i'm using functions from http://www.json.org/json2.js
var info = new Array(max);
for (var i=0; i<max; i++) {
var coordinate = [25 , 32];
info[i] = coordinate;
}
var result = JSON.stringify(info);
But result doesn't look like a JSON string at all. What am I doing wrong here?
You, and many in this question, are confused about the JSON specification. The string you have is a valid JSON array.
From json.org
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.
Your example matches the second structure - the ordered list of values.
Also from json.org:
An array is an ordered collection of
values. An array begins with [ (left
bracket) and ends with ] (right
bracket). Values are separated by ,
(comma).
A value can be a string in double
quotes, or a number, or true or false
or null, or an object or an array.
These structures can be nested.
Doesn't leave much to the imagination. You've got a valid JSON array there. Have fun with it. But just to be annoyingly thorough:
From the RFC
RFC 4627, Section 2
2) JSON Grammar
A JSON text is a sequence of
tokens. The set of tokens includes
six structural characters, strings,
numbers, and three literal names.
A JSON text is a serialized object
or array.
JSON-text = object / array
The result looks like this for me:
[[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32]]
Which is fine as far as I can see. It might look a bit weird, but that is mostly because JSON is used a lot for objects, which have a slightly different notation. You can eval the string and get the array structure back though, so it looks fine to me.

Categories