JSON split value at first space - javascript

I'm very new to JSON and I have not found the answer searching. I'm thinking my question is just too simple
I have a simple JSON
{
"Application": "The Best Application",
}
My goal is to split the value at the first space and store the next word in a variable, which in this case would be the word Best
I've tried the following, but it is not working:
var json = '{"Application":"The Best Application",}';
var obj = JSON.parse(json);
var obj2 = obj.result.split(" ");
console.log(obj2.result);

.split() returns an array and you want to take an item under index 1. Also note that JSON.parse() returns an object and you want to read the value from Application key:
var json = '{"Application":"The Best Application"}';
var obj = JSON.parse(json);
var obj2 = obj["Application"].split(" ");
console.log(obj2[1]);

Related

convert json values in comma separated string using javascript

I am calling a third party web api, which returns data like this:
{"name":"Marine Lines","name":"jerry"}
I would like to convert this to a Json array, I could do a split by comma first and then by ":". but wondering if there are some better ways?
If the Web API return an object, then you can directly use dot-notation to access the value.
var x = {"name":"Marine Lines","name":"jerry"};
var name = x.name;
console.log(name);
Else if it is a string then you can parse it first using JSON.parse() and then do the same thing.
var x = '{"name":"Marine Lines","name":"jerry"}';
x = JSON.parse(x);
var name = x.name;
console.log(name);
First of all, your object has the name key twice, which means only the latter will be saved. As regards saving your object's values in an array, the following will do:
var
object = {"a": "Marine Lines", "b": "jerry"},
array = [];
/* Iterate over every enumerable property of the object. */
for (var key in object) {
/* Insert the value in the array. */
array[array.length] = object[key];
}
/* Log the created array. */
console.log(array);

Can we iterate through json in javascript without using for..in

I have a requirement to throw a 400 Bad request error if the json payload contains duplicate keys. I am using below code to fetch all attributes in an array.
var arrayObj = [];
var attrArr = [];
var arr = {
"serviceNumer": "1612045709",
"customerRefNumber": "TCreateS9",
"customerRefNumber": "TCreateS9"
};
for (var key in arr) {
arrayObj.push(key, arr[key]);
}
console.log("arrayObj", arrayObj);
for (var i = 0; i < arrayObj.length; i = i + 2) {
attrArr.push(arrayObj[i]);
}
console.log(attrArr);
When I iterate using for..in, the duplicate keys get overridden. So please help me with any alternate approach.
JavaScript objects cannot have duplicate keys. All the keys must all be unique.
Go through the following links, this will clear your doubts StackOverflow JSObj and Finding and solving issues for duplicate keys
your JSON impementation can't handle duplicate keys,
if you take the object you've got from the JSON and convert it back to JSON, and then compare the number of colons in the string against the original. If there are duplicate keys in the original there will be fewer colons in the new JSON.
Such a check is suitable to give warning messages to noobs, but it's not bulletproof. An attacker could use escapes for colons in string values resulting in an increased count. if the requiremnt is critical you'll need to modify the JSON parser to do the check.
A JSON Object can't have duplicate Keys.
If you are getting your payload as string than you can do following:
var input = '{"serviceNumer":"1612045709","customerRefNumber":"TCreateS9","customerRefNumber":"TCreateS9"}';
if(input === JSON.stringify(JSON.parse(input)))
console.log("input has No Duplicate");
else
console.log("input has Duplicate");
here JSON.parse will convert input to JSON object and will remove duplicate keys
Hope this help you:)
you just dont know, keep do it
//you can hard code it or write it
var arr = {
"serviceNumer": "1612045709",
"customerRefNumber": "TCreateS9",
"customerRefNumber": "TCreateS93333"
};
//but when you call it it just will show the last element
console.log(arr.customerRefNumber)
/*
its like you say
var ac = 1
var ac = 3
console.log(ac)
it will show 3
*/
//make it different
var arr2 = {
"serviceNumer": "1612045709",
"customerRefNumber": "TCreateS9",
"customerRefNumber2": "TCreateS9"
};
var a = Object.getOwnPropertyNames(arr).sort()
var b = Object.getOwnPropertyNames(arr2).sort()
console.log(a)
console.log(b)

Javascript: how to access each element in an array

I query two arrays from the database and turn them into json format. The set up is like this:
{"groups":"[apple,bee,car,dogs,egos,fruits]", "members":"[g,h,i,j,k,l]"}
I am trying to access each element in groups. The groups array is a list. I tried using index, and it's returning me groups[0] = 'a', groups[1] = 'p'... So using index doesn't work.
I also want to count how many elements in the groups array or in the members array, and using .length only give me back the character length, not the actual numbers of elements.
Any advice would be appreciated. Thanks.
JSON.parse(groups) will not work, because [apple,bee,car,dogs,egos,fruits] is not correct JSON string.
["apple","bee","car","dogs","egos","fruits"] - is correct JSON string, that can be parsed.
P.S. members is not correct JSON string too.
// If you have some data
data = {
groups: ["apple", "bee", "car", "dogs", "egos", "fruits"],
members: ["g", "h", "i", "j", "k", "l"]
};
// you can convert it to JSON string
jsonData = JSON.stringify(data);
console.log('JSON data: ', jsonData);
// and then parse this string
restoredData = JSON.parse(jsonData);
// after this you can access object members again
console.log('groups[0]: ', restoredData.groups[0]);
This is happening because "[apple,bee,car,dogs,egos,fruits]" it's an string. You have to parse it before accessing the element.
Let's say that you have the JSON in the variable test, then we have to delete [ and ] and split the string like this:
test.groups = test.groups.replace("[", "")
test.groups = test.groups.replace("]", "")
test.groups = test.groups.split(',')
And then now it contains:
["apple", "bee", "car", "dogs", "egos", "fruits"]
You should consider constructing the array differently from the database.
You are getting those letters because they are in the position in the string that you are referencing with the index.
Consider using regex and the split() function to parse them as they are now:
var obj = {"groups":"[apple,bee,car,dogs,egos,fruits]", "members":"[g,h,i,j,k,l]"};
// Regex replaces the square brackets with blank spaces and splits by the
// comma into an array
var groups = obj.replace(/[\[\]']+/g,'').split(',');
var members = obj.replace(/[\[\]']+/g,'').split(',');
Now groups[1] will return 'bee'.
Read more about split() here.
It doesn't work because all elements of the array are in one string.
As has been mentioned this not correct JSON formatting, but sometimes you don't have control over how you get information. So although this is not a recommended answer, you could use simple string parsing to get back the values you want by doing, something like:
var stuff = JSON.parse('{"groups":"[apple,bee,car,dogs,egos,fruits]", "members":"[g,h,i,j,k,l]"}');
var groups = stuff.groups.split("[")[1].split("]")[0].split(",");
var members = stuff.members.split("[")[1].split("]")[0].split(",");
console.log(groups); // ["apple", "bee", "car", "dogs", "egos", "fruits"]
console.log(groups[1]); //bee
console.log(members[0]); //g
I would like to reiterate this is not an ideal solution, but sometimes it is all you can do.

Why an object key's first value is treated as a string - AngularJs

I have an object named as "param" and it has a key named as "item[]". The values of item[] are inserted dynamically.
Problem is when "item[]" has a single value, it treats that value as a string and not as first index of array.
Example :
item[]="123";
but when it has multiple values then it treats itself as an array which is desired, example-
item[] = ["123","456"];
I want the single value also as index of this array like
item[] = ["123"]
How would I do it ?
P.S. - This object is created from querystring parameters like http://example.com/def?item[]=123&item[]=456, then when I extract querystring, it returns these parameters as the keys of an object
I am extracting querystring in this way(Javascript)-
var param = $location.search();
console.log('Param');
console.log(param);//Returns Object{item[]=[2]} in console
This is because variableName[] is not a javascript syntax.
Since it does not recognise the [], it is probably part of the name if it does not throw an error.
To create an array, you have 2 possibilities :
//Contsructor
var ar = new Array(); //empty array
//Literal
var ar = []; //same as above
var ar = [0,1,2,3]; //array of length 4
var ar = new Array(4); //empty array of length 4
to access or set it
var ar[0] = "value"
Try this
queryString = ["123"];
queryString = ["123","432","456"];
if(queryString.length==1){
item.push(queryString[0]);
}else{
angular.forEach(queryString,function(value,key){
item.push(value);//push only value
})
}
I have solved it -
if(typeof param['item[]'] == "string"){
param['item[]'] = [param['item[]']];
}
First I am checking if the key has a string value, if it is string then I am converting it into an array and it worked.
Here is the working fiddle -
https://jsfiddle.net/r3vrxzup/

Javascript : How do I call the array index of the string?

Hello I have a problem when you change the string in order to invoke an array in javascript, please help me,
I have had a array:
var fruit=['Apple','Banana','Orange'];
and I have data string from mysql:
example: var string = '0,2';
How to display an array of fruit which corresponds to the var string?
(Thanks for the help)
You have to split() the string to get an array of indexes instead of a string of indexes :
var indexes = '0,2'.split(','); //use the ',' char to split the string
Now, you have to pick fruits values corresponding to each index in the new indexes array create just before.
var res = []; //The new Array to contains new fruits
indexes.forEach(function(index) { //loop over fruit indexes we want
res.push(fruit[index]); //Add the juicy fruit :)
});
And you got the new array (res) with the juicy fruits :)
JSFiddle
EDIT:
Or, a shorter/nicer solution (thanks to Xotic750)
(the second argument of the map function specify the context (this))
var ids = '0,2';
var fruits = ['Apple','Banana','Orange'];
fruits = ids.split(',').map(function(index) {
return this[index];
}, fruits);
I don't know if it will work or not, but this is what I could think of:
var x = [];
for (var i = 0; i>=string.length; i+=2) {
x.push(fruit[string[i]]);
}
But use only even numbers as a comma is also present in the string.
You will need to split the string into an array by using the Split() method:
var myArray = string.split(",");
Then you can loop over the array and use its values as indexes in the fruit array. For example, the first fruit will be:
fruit[myArray[0]];

Categories

Resources