I passed back a JSON object from a service and converted it to a string using JSON.stringify but the required output is not as expected as shown in the first example below:
What it looks like after stringify call on the JSON object:
[{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}]
What it needs to look like:
["98798 TestApp","98799 TestApp Two"];
How can I convert a JSON object to a presentable javascript array?
What I've tried -
I tried calling first stringify which doesn't give the required format as shown above:
var ridAppList = JSON.stringify(dataRID);
I also attempted converting that stringified string to a JS array using parseJSON but I get a result like - [object Obect], [object Object]:
var ridAppList = $.parseJSON('[' + ridAppList + ']');
This is the complete assignment for context. Inside the success function of an Ajax GET call a JSON object is returned
success: function (result) {
var dataRID;
dataRID = result;
ridAppList = JSON.stringify(dataRID);
alert(ridAppList);
},
You could use the array and build a new one with Array#map
var array = [{ "RID": "98798", "appName": "TestApp" }, { "RID": "98799", "appName": "TestApp Two" }],
result = array.map(function (a) {
return a.RID + ' ' + a.appName;
});
console.log(result);
The answers here are valid for your example, but here's a solution for arbitrary property quantity and names.
var flatObjects = [
{"RID":"98798","appName":"TestApp"},
{"RID":"98799","appName":"TestApp Two"},
{"ABB":"98799","appMode":"Test", "feature": 2}
].map(function (obj) {
var values = Object.keys(obj).map(function (key) {
return obj[key]
})
return values.join(' ')
})
var result = JSON.stringify(flatObjects)
console.log(result)
Edit: Code formatting.
After you parsed JSON you can use map() like this
var string = [{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}];
var result = string.map(function(e) {
return e.RID += ' ' + e.appName;
});
console.log(result)
Or with ES6 you can just do this
var string = [{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}];
var result = string.map(e => e.RID += ' ' + e.appName);
console.log(result)
This answer also uses Array.prototype.map but combines ES6 destructuring, arrow functions, and template literals for an especially concise procedure.
var input = [
{"RID":"98798","appName":"TestApp"},
{"RID":"98799","appName":"TestApp Two"}
];
var output = input.map(({RID, appName})=> `${RID} ${appName}`);
console.log(output);
// [
// "98798 TestApp",
// "98799 TestApp Two"
// ]
Related
I have such a object and array which I received response from my server. I need to convert that to second format at below in order to print the value in the website. Is this something need to do object mapping? or parse JSON or please kindly help.
{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]},
Convert from Above to below
'{"SEOUL" : "38", "BUSAN" : "CAPITAL", "NAMPODONG" : "M31"}'
var finalObj = {};
response.header.forEach(function(item, index) {
finalObj[item] = response.data[0][index];
});
Above code is working fine as it create variable and loop for header and get its value and printed in html. the header and data are from the server so when I enter something let say "A" then it will look for SEOUL header then print 38 in html as tables are looks below.
key value : A
header : SEOUL BUSAN NAMPODONG
data : 38 CAPITAL M31
I do have a lot of data in the database, above is just an example. So let say I enter B then the B is not in database so I want to see the value "No found" in html but this code printing nothing so not sure whether it was proceed or not.
Create a variable & loop over the object.header to get each key and object.data[0] to get its value
var myObj = {
"header": ["SEOUL", "BUSAN", "NAMPODONG"],
"data": [
[38, "CAPITAL", "M31"]
]
}
var tempObj = {};
myObj.header.forEach(function(item, index) {
tempObj[item] = myObj.data[0][index]
})
console.log(tempObj)
As you received it from server – I assume that it is JSON string.
Basically you have two arrays here that you want to reduce to an object.
So I would do it like this:
const object = JSON.parse('{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}');
const result = object.header.reduce(function(accumulator, element, i){
accumulator[element] = object.data[0][i] // You had nested array here so I have to get first element.
return accumulator;
}, {});
console.log(result);
I assumed that nested array for data attribute is some kind of formatting mistake. If it's not – you have to map though it's elements first and only then reduce.
You can use zipObj from Ramda library.
The code would look like this:
const res = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}
const obj = R.zipObj(res.header, res.data[0])
console.log(obj)
<script src="//cdn.jsdelivr.net/npm/ramda#latest/dist/ramda.min.js"></script>
You could map the new objects with the wanted keys.
The result is an array with objects, because your data is a nested array with actually only one array. But it looks like taht data could contain more than one row.
var data = { header: ["SEOUL", "BUSAN", "NAMPODONG"], data: [[38, "CAPITAL", "M31"]] },
result = data.data.map(a => Object.assign(...data.header.map((k, i) => ({ [k]: a[i] }))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can map the data array of arrays into another array of object using as keys the strings in header array:
function transform(obj) {
return obj.data.map(function(subArray) { // for each subArray in the data array
return subArray.reduce(function(o, val, i) { // create a new object o which...
o[ obj.header[i] ] = val; // has key-value pairs where value is the current element of subArray and key is its equivalent (item at the same index) from header array
return o;
}, {});
});
}
var obj = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"], [10,"OTHER","M01"]]};
var result = transform(obj);
console.log(result);
I think the responses above are good as they are, but here is an alternative using reduce in case you didn't know about it
var response = {
"header": ["SEOUL", "BUSAN", "NAMPODONG"],
"data": [
[38, "CAPITAL", "M31"]
]
};
var result = response.header.reduce(function(accum, v, i) {
accum[v] = response.data[0][i];
return accum;
}, {})
console.log(result)
I am trying to convert to object this string.
"JwtBody { user_id: 1, auth_id: 1}"
"JwtBody { user_id: 1, auth_id: 1}" is obviously not a standard json string,So you can try this.
function strToObj(str){
var obj = {};
if(str&&typeof str ==='string'){
var objStr = str.match(/\{(.)+\}/g);
eval("obj ="+objStr);
}
return obj
}
Could you use JSON.parse()?
I haven't used it myself, but it looks like create a variable and use JSON.parse("string") to have it converted into an object.
So, for your example it would be something like:
var object = JSON.parse("JwtBody { user_id: 1, auth_id: 1}");
Not exactly sure what you're trying to do.
You could try something like this:
var str = '{"user_id": "1", "auth_id": "1"}';
var obj = $.parseJSON(str);
Be sure to have jquery like this:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
If you can't change data from example:
var parsedData = {};
var str = "JwtBody { user_id: 1, auth_id: 1}";
function getRawJSON(str){
return str.split(' ').map((el, index)=>{return index>0 ? el : ''}).join('');
}
function formatingValidJSON(str){
// From https://stackoverflow.com/questions/9637517/parsing-relaxed-json-without-eval
return str
.replace(/:\s*"([^"]*)"/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
.replace(/:\s*'([^']*)'/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')
.replace(/#colon#/g, ':')
}
str = formatingValidJSON(getRawJSON(str));
try{
parsedData = JSON.parse(str);
console.log('Your parsed data:', parsedData);
}
catch(e){
console.log('Your data is wrong');
}
This JSON-like string can be parsed using vanilla JavaScript and regex by:
Reducing string to only characters that String.match() JSON-like object string
String.replace() property names to enclose matched names with quotations
parsing object with JSON.parse
var jwtBodyString = "JwtBody { user_id: 1, auth_id: 1}";
`//1 match on only JSON within string
jwtBody = jwtBodyString.match(/{[^}]+}/).toString();`
//2 enclose property names to prevent errors with JSON.parse()
jwtBody = jwtBody.replace(/([a-zA-Z]+):/g,'"$1":'));
//3 obtain object
var myJwtBodyObject = JSON.parse(jwtBody);
Use JSON.parse()
Also, you're javascript string is invalid JSON which means it's invalid javascript. It should look like this:
JSON.parse('{"jwtbody" : { "user_id" : 1, "auth_id" : 1}}');
This will give you the corresponding javascript object you want.
JSON contains one object:
results[0] = { 'MAX(id)': 1 }
And this code doesn't work:
var text = results[0];
var obj = JSON.parse(text);
console.log(obj.MAX(id));
results[0] is already an object type
You can parse only from string to object like this:
JSON.parse('{ "MAX(id)": 1 }');
Your object is already a JSON. You don't need to parse it.
To access MAX(id) property, you can use [] notation as follows:
results[0] = { 'MAX(id)': 1 };
console.log(results[0]['MAX(id)']);
Your result[0] is a real javascript object. JSON.parse transforms text into objects, so you can't parse other objects with it.
var results = { 'MAX(id)': 1 };
//var text = results;
//var obj = JSON.parse(text);
alert(results['MAX(id)']);
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/
I have an js object like
{
a: 1,
b: 2,
c: 3
}
I wanted to stringify the above object using JSON.stringify with the same order. That means, the stringify should return me the strings as below,
"{"a":"1", "b":"2", "c":"3"}"
But it is returning me like the below one if my js object has too many properties say more than 500,
"{"b":"2", "a":"1", "c":"3"}"
Is there any option to get my js object's json string as in sorted in asc.
If the order is important for you, don't use JSON.stringify because the order is not safe using it, you can create your JSON stringify using javascript, to deal with string values we have 2 different ways, first to do it using regexp an replace invalid characters or using JSON.stringify for our values, for instance if we have a string like 'abc\d"efg', we can simply get the proper result JSON.stringify('abc\d"efg'), because the whole idea of this function is to stringify in a right order:
function sort_stringify(obj){
var sortedKeys = Object.keys(obj).sort();
var arr = [];
for(var i=0;i<sortedKeys.length;i++){
var key = sortedKeys[i];
var value = obj[key];
key = JSON.stringify(key);
value = JSON.stringify(value);
arr.push(key + ':' + value);
}
return "{" + arr.join(",\n\r") + "}";
}
var jsonString = sort_stringify(yourObj);
If we wanted to do this not using JSON.stringify to parse the keys and values, the solution would be like:
function sort_stringify(obj){
var sortedKeys = Object.keys(obj).sort();
var arr = [];
for(var i=0;i<sortedKeys.length;i++){
var key = sortedKeys[i];
var value = obj[key];
key = key.replace(/"/g, '\\"');
if(typeof value != "object")
value = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
arr.push('"' + key + '":"' + value + '"');
}
return "{" + arr.join(",\n\r") + "}";
}
The JavaScript objects are unordered by definition (you may refer to ECMAScript Language Specification under section 8.6, click here for details ).
The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.
If you still required sorting, convert the object into Array apply any sorting algorithm on it and then do JSON.stringify() on sorted array.
Lets have an example below as:
var data = {
one: {
rank: 5
},
two: {
rank: 2
},
three: {
rank: 8
}
};
var arr = [];
Push into array and apply sort on it as :
var mappedHash = Object.keys( data ).sort(function( a, b ) {
return data[ a ].rank - data[ b ].rank;
}).map(function( sortedKey ) {
return data[ sortedKey ];
});
And then apply JSON.stringy :
var expectedJSON = JSON.stringify(mappedHash);
The output will be:
"[{"rank":2},{"rank":5},{"rank":8}]"