I am returning a JSON array string from c#, which is a list of classes I want to read county element in a class and add it to a js array. How can I parse this string?
{"d":"[{\"county\":\"PA\",\"state\":\"Mountur\"},{\"county\":\"PA\",\"state\":\" Beaver\"}]"}
The d property is itself JSON, so you need to parse that separately from the response to give you an array of objects which you can work with, something like this:
var response = {
"d": "[{\"county\":\"PA\",\"state\":\"Mountur\"},{\"county\":\"PA\",\"state\":\" Beaver\"}]"
}
var arr = JSON.parse(response.d);
arr.forEach(function(obj) {
console.log(obj.county + ' ' + obj.state);
});
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 Have a string like
[ "Basic, JavaScript, PHP, Scala" ]
How to convert it like
[ 'Basic', 'JavaScript', 'PHP', 'Scala' ]
code
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
var a = localStorage.getItem(localKeyChief);
var Item = JSON.stringify(a); // it show like ["Basic, JavaScript, PHP, Scala"]
}
JSON.stringify() returns a String so your question is incorrect. Item is not an Array.
const Item = '["Basic, JavaScript, PHP, Scala"]';
Therefore you should not use it. Instead simply return the array a in your function:
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
return localStorage.getItem(localKeyChief); // <-- no use of JSON.stringify()
}
This way loadDataToGridChiefComplaint() is the array ["Basic, JavaScript, PHP, Scala"], it has a single element of type String that you can access with the bracket notation Item[0]:
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0]);
So in order to convert the string Item[0] into an array, use the .split method:
String.split(separator)
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
MDN Web Docs
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0].split(', '));
If you can't modify this function you can use the opposite operation of JSON.stringify which is JSON.parse to convert the string back to an array:
const ItemString = '["Basic, JavaScript, PHP, Scala"]';
ItemArray = JSON.parse(ItemString);
And then use .split (like the previous example) to get the array of strings.
Try this :
var Item = ["Basic, JavaScript, PHP, Scala"];
// Do like this
var array = Item[0].split(', '); // Split with Comma and space(for trim whitespace)
// Or Like this
var array = Item[0].split(',').map(i => i.trim()) // Split with comma and use map to trim whitespace
console.log(array);
I have a json string
["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]
I need to get at the data only and I want to extract the string to get the following :
https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
I have tried to use JSON.parse but this does not seem to work
Any help woul dbe appreciated
[] represents an array on JSON. {} represents an Object.
So in order to fetch the first element from you json string, you have to parse the string as a JSON element ;
var arr = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]');
OR when you HAVE a json array already;
var arr = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
Then, go on and fetch the first value from your array which has index 0 as in all programming languages.
var url = arr[0];
It's seems to be a normal array not a JSON, but if you want you can treat it as JSON:
var image = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]')[0];
console.log(image); //https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
Be aware of the difference between an array, and a JSON object.
I have given some examples of the differences and how to access them.
// This is an array containing 1 value.
myobj = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
// it can be accessed by either the array name (since it only hase one value) or the array name and index of the value in cases where the array actually has more than one value.
var example1 = [myobj];
document.write("This is my single value array:<br>" + example1 + "<br><br>");
// This is probably best practice regardless of the number of items in the array.
var example2 = myobj[0];
document.write("Now im specificing the index, incase there are more that one urls in the array:<br>" + example1 + "<br><br>");
// This is a JSON object
myJsonObj = {"url":"https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"}
// You access the value of the URL like this:
var example3 = myJsonObj.url;
document.write("Here is the value from a JSON object:<br>" + example3 );
Hope this helps
Just use parse function:
var text = '["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]';
var obj = JSON.parse(text);
https://jsfiddle.net/esouc488/1/
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 have a Json data as listed below:
var x = {
"array1":"['x1','x2']",
"array2":"['a1', 'a2']"
}
I need to print the individual elements of the array as below
x1
x2
a1
a2
When I do var y = JSON.parse(x), it gives me "Unexpected token o"
It seems to be coming from the JSON.parse line. If I do x = '["x1", "x2"]', there is no error but I need to have two arrays in the JSON. So how do I read them
Thanks for any answers
That is not JSON. JSON is a string and not an object hence its abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old JavaScript Object. They are different. The former is a data exchange format similar to YAML or XML while the latter is an actual object with properties and values.
Your POJO does have JSON values but since it is already an object you can't use JSON.parse to parse the entire object. That is where the "o" is coming from in the error message. JSON.parse will coerce the first argument to a string if it is not a string:
var foo = {};
JSON.parse(foo); // is essentially doing this foo.toString() which is "[object Object]"
JSON.parse('{}'); // This would parse to an empty object though since it is a string
So now when it attempts to parse "[object Object]" it sees what may be an array but then encounters a character that hasn't been quoted, the "o" in "object", and therefore throws an error.
For your example to be JSON you would need to write it as:
var json = '{"array1":["x1","x2"],"array2":["a1","a2"]}';
var x = JSON.parse(json);
document.write('<pre>' + JSON.stringify(x, null, 4) + '</pre>');
And so, now that we have a real JSON value we can answer your original question:
var json = '{"array1":["x1","x2"],"array2":["a1","a2"]}';
var x = JSON.parse(json);
var vals = Object.keys(x).sort().reduce(function (arr, key) {
arr = arr.concat(x[key]);
return arr;
}, []).join('\n');
document.write('<pre>' + vals + '</pre>');
I think your JSON should be like the following
{
"array1": ["x1", "x2"],
"array2": ["a1", "a2"]
}
Create your array in many different ways - two examples
var x = [{array1:['x1','x2']},{array2:['a1','a2']}]
x[1].array2 produces ["a1", "a2"]
x[1].array2[0] produces "a1"
var xx = {array1:['x1','x2'],array2:['a1','a2']}
xx.array2 produces ["a1", "a2"]
xx.array2[0] produces "a1"
third example
var xxx = {array1:{x1:'x1',x2:'x2'},array2:{a1:'a1',a2:'a2'}}
xxx.array1.x1 produces "x1"
What you have there, that 'x' variable var x = {"array1":[...]...} is already a javascript object, so you can simply pass through the object keys and display the values.
Given 'x' as the object you can have something like:
var key,
result = '';
for (key in x) {
if (x.hasOwnProperty(key)) {
result = result + x[key].join('\n') + '\n';
}
}
// There you have the result...
As John said earlier, for JSON.parse() you wold need a string as a parameter to be able to parse it into a javascript object.
so, you can use this script to do that (correct json too - http://jsonformatter.curiousconcept.com/ -, don't know why this downrate.....i guess a noob didnt realize :D):
var x = {
"array1": ["x1", "x2"],
"array2": ["a1", "a2"]
}
for (var key in x) {
if (x.hasOwnProperty(key)) {
document.getElementById("test").innerHTML += key + " -> " + x[key]+" <br>";
}
}
i've created a working fiddle here:
https://jsfiddle.net/rjzzqLmr/1/