I'm writing a method which should concatenate two strings(that are result of json stringify) into one string(which should look like json object with it's structure).
First one :
{"text":"klk","makeId":"9"}
Second one:
{"firstname":"jjk","lastname":"jkjk","email":"jjkjk#sdasd.com"}
How do I concatenate these two into one json string i.e :
{"text":"klk","makeId":"9", "firstname":"jjk","lastname":"jkjk","email":"jjkjk#sdasd.com"}
I could strip {" and "} then split by comma and achieve this result. I'm wondering is there better more smart way to do this?
These strings are JSON! Parse them, merge them like objects and stringify them again.
var data1 = JSON.parse(json1);
var data2 = JSON.parse(json2);
var data = merge(data1, data2); // implement merge!
console.log(JSON.stringify(data));
JSON should be available in all recent browsers.
function merge(obj1, obj2) {
var hasOwn = {}.hasOwnProperty;
for (var key in obj2) {
if (hasOwn.call(obj2, key)) {
obj1[key] = obj2[key];
}
}
return obj1;
}
Related
I must be missing something here, but the following code (Fiddle) returns an empty string:
var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
What is the correct way of JSON'ing this array?
JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.
The JSON array data type cannot have named keys on an array.
When you pass a JavaScript array to JSON.stringify the named properties will be ignored.
If you want named properties, use an Object, not an Array.
const test = {}; // Object
test.a = 'test';
test.b = []; // Array
test.b.push('item');
test.b.push('item2');
test.b.push('item3');
test.b.item4 = "A value"; // Ignored by JSON.stringify
const json = JSON.stringify(test);
console.log(json);
Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.
if(window.Prototype) {
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
delete Hash.prototype.toJSON;
delete String.prototype.toJSON;
}
it works fine and the output of the test:
console.log(json);
Result:
"{"a":"test","b":["item","item2","item3"]}"
I posted a fix for this here
You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Another approach is the JSON.stringify() replacer function param. You can pass a 2nd arg to JSON.stringify() that has special handling for empty arrays as shown below.
const arr = new Array();
arr.answer = 42;
// {"hello":"world","arr":{"answer":42}}
JSON.stringify({ hello: 'world', arr }, function replacer(key, value) {
if (Array.isArray(value) && value.length === 0) {
return { ...value }; // Converts empty array with string properties into a POJO
}
return value;
});
Alternatively you can use like this
var test = new Array();
test[0]={};
test[0]['a'] = 'test';
test[1]={};
test[1]['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
Like this you JSON-ing a array.
Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:
var json = JSON.stringify({whatver: test});
I have this String result:tie,player:paper,computer:paper
I guess you could split into arrays and make a object and parse it an object, however this does not seem to be a good approach.
How would I get this String as a object?
let string = "result:tie,player:paper,computer:paper"
For this particular string, I'd turn the string into proper JSON by surrounding the keys and values with "s, and then use JSON.parse:
const string = "result:tie,player:paper,computer:paper";
const json = '{' + string.replace(/(\w+):(\w+)/g, `"$1":"$2"`) + '}';
console.log(JSON.parse(json));
Though, ideally, whatever serves you that string should be giving you something in JSON format, rather than forcing you to resort to a hacky method like this to deal with a broken input.
Split on ,, iterate through, and split each string on : and make an object key/value property based on that. Use destructuring for simplicity:
let string = "result:tie,player:paper,computer:paper";
let obj = {};
let propsArr = string.split(",");
propsArr.forEach(s => {
var [key, value] = s.split(":");
obj[key] = value;
});
console.log(obj);
Split on the , to get key:value tokens, split those by : to get the key and value, and add them to the reduced object that collects the key value pairs.
var temp = "result:tie,player:paper,computer:paper";
var obj = temp.split(',').reduce((result, token)=>{
var [key, value] = token.split(':');
result[key] = value;
return result;
}, {});
console.log(obj);
im currently working on a project that uses javascript as it's front end and im having a bit trouble on adding a key on my existing array.
i have an object that i wanted to be converted on array javascript.
here is my code on how to convert my object to array.
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) { return obj[key]; });
var site_key = $.map( obj, function( value, key ) {
return key;
});
the site_value has the value of my objects.
the site_key has the key.
i want to add my site_key to the site_value array as a Key.
example data:
site_value:
0:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
site_key:
Array[49]
0:"AGB"
1:"BAK"
2:"BAN"
3:"BAR"
i want my array to be
AGB:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
Update:
Here is my object.
Array[1]0:
Object
AGB: Array[4]
BAK: Array[4]
BAN: Array[4]
etc.
You have almost done it and I have modified it a bit below to return it as array object,
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) {
var output = {};
output[key] = obj[key];
return output;
});
I might be misunderstanding the question, sorry if I am. I think you would like to use a key "AGB" instead of an integer for an array index. In this case, you would probably be better served to use an object instead of an array. Maybe something like this
var myObject = {
AGB: Array[4],
AGBarrays: [Array[4],Array[1],Array[1],Array[0]]
};
Then you could access AGB by key and your additional arrays by index
I got a very common question but with a twist which is the reason for this post:
I want to create a key,value object from a string.
my string looks like this:
01§§foo§§bar§§someLink
(i can change the delimiter symbols to whatever i want, if there should be somehow a very tight solution with a specific symbol)
now, i want a key value object and most questions about this problem already got the datapair in the string,(like "id:01,title:foo") but thats not the case in my problem.
i want to generate something like this:
var modules = [
{"ID":"01", "title":"foo", "description":"bar","link":"someLink"},
//more entries from more strings
];
the reason for the key,value object is, that there are more of these strings which I convert from a database. I want it to be in a key,value object so its easier to work with the data later in my tool.
Thank you in advance
You could use Array#split for the string and an array for the keys.
var string = '01§§foo§§bar§§someLink',
moduleKeys = ["ID", "title", "description", "link"],
object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
console.log(object);
A methode for multiple strings.
function getData(array) {
var moduleKeys = ["ID", "title", "description", "link"];
return array.map(function (string) {
var object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
return object;
});
}
var strings = ['01§§foo§§bar§§someLink', '02§§foo§§bar§§someLink'];
console.log(getData(strings));
How do I change a JSON object into an array key/value pairs through code?
from:
{
'name':'JC',
'age':22
}
to:
['name':JC,'age':22] //actually, see UPDATE
UPDATE:
...I meant:
[{"name":"JC"},{"age":22}]
May be you only want understand how to iterate it:
var obj = { 'name':'JC', 'age':22 };
for (var key in obj)
{
alert(key + ' ' + obj[key]);
}
Update:
So you create an array as commented:
var obj = { 'name':'JC', 'age':22 };
var obj2 = [];
for (var key in obj)
{
var element = {};
element[key] = obj[key]; // Add name-key pair to object
obj2.push(element); // Store element in the new list
}
If you're trying to convert a JSON string into an object, you can use the built in JSON parser (although not in old browsers like IE7):
JSON.parse("{\"name\":\"JC\", \"age\":22}");
Note that you have to use double quotes for your JSON to be valid.
There is no associative array in JavaScript. Object literals are used instead. Your JSON object is such literal already.