I get the data from database, but when I try to parse it with json parse an error accrue indicating this is not a valid json format. (because its values are not in quotation).
I can not make any changes to data valuable & I prefer not to use replace if possible!
var data = "a,b,c";
data = JSON.parse('['+ data +']'); //error because there is no quotation marks
Is there any other JavaScript function that can be used to parse the value of data into json or even array.
As said in the comments, your data has not JSON format, so don't try to parse it as JSON.
Instead, it seems it represents a comma-separated list of values. To obtain an array with these values you can use String.prototype.split.
And then, to wrap each item in an object, you can use Array.prototype.map:
"a,b,c".split(',').map(function(item) {
return {0: item};
});
Simplifying with ES6 arrow functions,
"a,b,c".split(',').map(i => ({0:i}));
Try:
var data = "a,b,c".split(',');
obj = [];
for (var i = 0; i < data.length; i++)
{
obj.push({'0': data[i]});
}
use split() Method to split your string into an array of substrings
var data = "a,b,c";
data = data.split(',');
arr = [];
for(var i = 0; i < data.length; i++){
arr.push({0: data[i]})
}
console.log(data);
console.log(arr);
Related
I want to convert a JSON string into a set of array containing the values from the JSON. after json.stringify(jsonmybe) and alert it display [{"role":"noi_user"},{"role":"bert_user"}] (which i saw as a JSON). I want to get the noi_user and bert_user and set them into a javascript array. something like ['noi_user','bert_user'] with quotes in each value.
I did the var stringy = json.parse() and the alert showing [object Object]. and further add this lines
for (var i = 0; i < stringy.length; i++) {
arr.push(stringy[i]['role']);}
and the arr I get was a value with comma when in alert but the comma missing as i display them in the text field and it becomes a long string like noi_userbert_user
What I really want is from [{"role":"noi_user"},{"role":"bert_user"}] to ['noi_user','bert_user']
Use JSON.parse and then reduce to get what you want,
var s = `[{"role":"noi_user"},{"role":"bert_user"}]`
var arr = []
try {
arr = JSON.parse(s).reduce((acc, val)=>[...acc, val.role], [])
} catch (e){
console.log("Invalid json")
}
console.log(arr)
Is this what you are loking for ? You can map on your array and just extract the role attribute of each datum.
const jsonString = ...
const data = JSON.parse(jsonString).map(data => data.role);
console.log(JSON.stringify(data, null, 2));
JSON uses double quotes to delimit strings and field names.
So you have a JSON string like
'[{"role":"noi_user"},{"role":"bert_user"}]'
You want to convert it to an object, then extract values of "role" fields of each element, put them all into an array.
Your example json string contains an array of user objects within "role" fields. Following code takes this list, loops through each user object and puts role's of each object into a separate array roleList.
var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
var userObjList = JSON.parse(jsonStr);
var roleList = [];
userObjList.forEach(userObj => {
roleList.push(userObj.role);
});
console.log(roleList);
You could make a custom function to produce a sort of array_values in PHP but an indented and 2D level like so:
function array_values_indented (input) {
var tmpArr = []
for (key in input) {
tmpArr.push(input[key]['role']);
}
return tmpArr
}
var object = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var result = array_values_indented(object);
console.log(result);
I am storing a json object in json array and assign it to another main json object, but when I print the value of main json object it display 1. Below is the code.
var jsonMainObject= {};
var jsonArray= [];
for(var j=0;j<cu.receivedData.length;j++) {
jsonMainObject["company"] = jsonArray.push(cu.receivedData[j].company);
}
console.log(jsonMainObject)
Below is the output
{ company: 1 }
But it should show the array. when i print jsonArray it shows the array of object, but when I console the output of jsonMainObject it displays the above output.
The push method returns the new length of the array. See documentation. I guess you should use:
jsonMainObject["company"].push(valueToPush)
or use concat (documentation)
jsonMainObject["company"] = jsonMainObject["company"].concat(valueToConcat)
There is no JSON at all here. JSON is a text format for representing data. What you have is a JavaScript object with a JavaScript array.
You are trying to put the array in the object at the same time as putting items in the array. The push method doesn't return the array that it was called on, it returns the length of the array. The company property will end up containing the length of the receivedData array.
You can put the array in the object from start:
var arr = [];
var mainObject = { company: arr };
for(var j = 0; j < cu.receivedData.length; j++) {
arr.push(cu.receivedData[j].company);
}
console.log(mainObject);
So, I have the following data here:
{"screenName":"fubars","msgHash":"C5STUYqhjzNiP6LLVbPlTF3zYLVYXHrm","imgURL":null,"userColor":"#00a4a0","messageTime":"2:50 PM","messageDate":1442256635621,"accountType":"m","accountTypeID":"z2ZkdXqck-JO45hqXVXH","isModerator":"","badges":""
I've written some regex to extract strings, but if I search for example "screenName" it gets the "fubars" part and the rest of the string, I only want the "fubars" part...
code:
function extractSummary(iCalContent, what) {
eval("var rxm = /\""+what+"\": \"(.*)\"/g");
console.log(rxm);
setTimeout(function(){},1500);
var arr = rxm.exec(iCalContent);
return arr[1];
}
If you have some data in the form of a JSON string, you can use JSON.parse to convert it into a JSON object. You can then use dot or index property getters.
var jsonString = '{"screenName":"fubars","msgHash":"C5STUYqhjzNiP6LLVbPlTF3zYLVYXHrm"}';
var jsonObject = JSON.parse(jsonString);
console.log(jsonObject.screenName);
console.log(jsonObject['screenName']);
There's no need to use regexes here.
I'm storing a bunch of values in localStorage. An array with JSON objects in it to be specific.
When I want to add another object to that array here is how I pull it, parse it, push onto the array and set it again.
var clickedItem = sessionStorage.getItem('location'),
interest = [],
interests = localStorage.getItem('interests');
interestsParsed = JSON.parse(interests);
interestsParsed.push(clickedItem);
localStorage.setItem('interests', JSON.stringify(interestsParsed));
Later on if I pull the array and loop through the array my properties are undefined.
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i].anything); // any property is undefined
}
PS. The JSON object looks completely normal when I console it. Any ideas why the props would be undefined?
UPDATE:
data is in fact an array and looping through it does give me each value from within it. However each JSON object in the array is no longer an object and must be JSON.parsed to "recreate" an object out of the string that it is.
This was a really great lesson on storing JSON objects within an array in localStorage.
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i].anything); // any property is undefined
var obj = JSON.parse(data[i]); // parse it instead
console.log(obj.title); // use it as an object now
}
My assumption is that you are trying to stringify a complex object, probably something like a DOM object or another built-in API's object. What happens is that JSON.stringify will strip the object out of all methods, and this includes internal setters and getters, and you remain with an empty (or almost empty) object.
My solution in such cases is to parse the complex object into a simple one containing only the properties you need in the formatting of your choosing.
JSON.parse() returns an object but you're treating it as an array. Instead of pushing to the array, add a new item to the object.
localStorage only supports strings. Use JSON.stringify() and JSON.parse().
//demo value
var clickedItem = {"testValue":111};
var interests = [{'a':1},{'b':2},{'c':4}];
localStorage.setItem('interests', JSON.stringify(interests));
//demo value end
interest = [],
interests = localStorage.getItem('interests');
interestsParsed = JSON.parse(interests);
interestsParsed.push(clickedItem);
console.log(interestsParsed);
localStorage.setItem('interests', JSON.stringify(interestsParsed));
var data = JSON.parse(localStorage.getItem('interests'));
for(var i = 0, j = data.length; i < j; i++ ){
console.log(data[i]);
}
I think you did't stringify value of interests,(before getting value at line no.3)
I have a key value pair something like this. this response comes back from the service in API.
var str = { "key1":"value1",..}
I need to use something lik this
for(var value in str) {
//I need to get only the value here. Eg: value1,value2 etc
}
how to get only value1 from this array using jquery sub string?
You can loop through an object (= key/value store) like this:
for (var key in items) {
var value = items[key];
// do things with key and value
}
If the response comes back as a set of (key, value) pairs, then you cannot really select the "first" value, because JSON objects do not have an order to their fields (different parsers may and probably will return the values in different order). You must know which key you want to access.
var str = { "key1":"value1",..}
for(var val in str) {
var strval = str[val];
}
var str = { "key1":"value1","key2":"value2","key2":"value2"};
var keyItems,valItems;
for(key in str){
keyItems.push(key);
valItems.push(str[key]);
}
// keyItems is array of all keys
// valItems is array of all values.