Replacing a property value in JSON - javascript

If I have a JSON structure that looks something like this:
var user = {
map: {
width: 785,
height: 791
},
image: {
name: "image.png",
size: {width:32}
},
properties:[{
firstName: "Bob",
lastName: "Jones",
}]
};
How would I change (after creation) the value of the firstName property to "Jane"?
I am fairly new to JSON, and I'm just trying to figure out how to make this one change for now. Any help would be greatly appreciated.

Well, one reason for your confusion might be that this is not JSON at all. JSON is a text format used for serialising objects. This is just a literal object in Javascript.
To change the firstName property, you would access the first item in the properties array in the user object:
user.properties[0].firstName = "Jane";

As long as the user variable is in scope:
user.properties[0].firstName = "Jane";

var changeName = function(obj, newName) {
obj.properties[0].firstName = newName;
return obj;
}

I saw this question and the solutions to it but my script still didn't work.
I found the solution and I figured I should post this here, it might save some people a little research.
My JSON result had some integers in it and it required the parseInt() function.
Taking the above example you probably have to do something like this.
user.map.width = parseInt(somevariable);
Since javascript is loosely typed I never really worry about it, but in this case it's necessary.

Related

Convert a string into a JS object that is not formatted correctly

My string is not formatted correctly, using JavaScript, let's say the data is:
{engine{type{condition},age},wheels,model{name},color}
And I want to convert that to a usable (JS) object. I could use regex to parse out pieces, but I'm wondering if there's a non-regex method to do so. If you had to do it in regex, what would be the easiest way of doing it?
Converted object should be something more like:
{
engine: {
type: {
condition: null
},
age: null
},
wheels: null,
model: {
name: null
},
color: null
}
I could also work with it from a series of nested arrays.
Well, under the assumption that that "char{" should be "char:{" and "char," or"char}" should be "char=null," or "char=null}", this is a pretty simple find and replace. Otherwise, you might have to use a recursive parse function to rip it apart and put it back together again.
var str = "{engine{type{condition},age},wheels,model{name},color}"
str = str.replace(/([A-z])\s*{/g, "$1:{")
str = str.replace(/([A-z])\s*([},])/g, "$1:null$2")
console.log(str);

Javascript: How to use Template Literals with JSON?

I discovered Javascript ES6 Template Literals today. Just one word: Awesome!
Question: How to store and load Template Literals as JSON? I load some files via XHR, followed by some JSON.parse() which doesn't support ` instead of ", so it seems one can't save Template Literals directly in the files.
Goal: To use this for dynamic strings and translation and to get rid of confusing stuff like ("Hello " + username + "! How are you?") which requires multiple strings to be stored for just one message, and instead save my stuff beautifully and simple as
`Hello, ${username}! How are you?`
where username points to the dynamic variable with the same name. Is that possible? If yes, how to achieve this? It's okay if i have to use a function to somehow convert the strings into Template Literals as long as it doesn't hit hard on the overall performance, but I would like to at least avoid eval.
You can create your own function to parse template literal,
function stringTemplateParser(expression, valueObj) {
const templateMatcher = /{{\s?([^{}\s]*)\s?}}/g;
let text = expression.replace(templateMatcher, (substring, value, index) => {
value = valueObj[value];
return value;
});
return text
}
console.log(stringTemplateParser('my name is {{name}} and age is {{age}}', {name: 'Tom', age:100}));
// output 'my name is Tom and age is 100'
You could always use JSON.stringify to enclose dynamic data:
const data = 'some value';
JSON.stringify({
data,
});
// expected: "{\"data\": \"some value\"}"
I found it easier to separate the problem in a few substrings of JSON. Create the key "message" and this key stores parts of the message. It also works well for i18n.
{
"message" : {
"_0": "first part ",
"_1": "after first variable. ",
"_2": "after another variable"
}
}
And then, after decoding it, you can access it like
${message._0}${variable}${message._1}${var2}${message._2}
Try json-templates. Looks like exactly what you're looking for.

Options and value won't display in ember-select-guru

I am trying to use ember-select-guru within my own component. The .hbs element looks like this. {{ember-select-guru multiple=true value=values options=options onSelect=(action "onSelect") and my .js looks like this
values: Ember.computed('user' function() {
const values = [];
this.get('user.listOfThings').forEach(value => {
values.push(value.get('name'));
});
return values;
}),
with a similar thing for the options array.
My problem is that the strings that are in value.get('name') are not displayed. It is definitely picking up the array because the right number of elements appear in the combobox but they are just empty div elements. The variable values ends up being an array of strings which seems to work normally everywhere else. Does someone know something I don't? I cant find anything in the docs or in the source code to help me.
I would also be open to using something else that behaves the same way. The is an example of how it should look in the docs.
I just found the answer. I looked at the source for the docs page and found that the component seems to be looking for an array of objects which have a name field. Luckily enough my list of things already had a name attribute and I just needed to call .toArray(). Code looked like this:
values: Ember.computed('user', function() {
return this.get('user.listOfThings').toArray();
}
However in a more general case you would need to use:
values: Ember.computed('user', function() {
var values = [];
this.get('user.listOfThings').forEach(value => {
values.push({ name: value.get('attributeYouWant'), other: other });
};
return values;
}
This is somewhat useful because an array of strings isn't all that functional but it maybe should be a little clearer than having to look at source code for a web page in the dev tools of your browser.

JSON element detection

I’ve created a string…
{"atts": [{"name": "wedw"}, {"type": "---"}]}
I pile a bunch of these together in an array based on user input and attach them to another string to complete a JSON object that tests out as valid.
So I end up with a global array called fields with a bunch of these little snippets.
So how do I change the name "weds" with a new name? I’ve tried...
function changefieldname(pos){
var obj = JSON.parse(jsonstring);
var oldname = obj.tracelog.fields[pos].atts[0]["name"];
var newname = document.getElementById("newlogfieldname"+pos).value;
fields[pos].replace(oldname, newname);
//writejson();
}
And a bunch of variations. I know everything is checking out correct interms of the variables pos, oldname, and newname. I also know that fields[pos] returns the string in the array I want to correct but it’s not happy. I also tried converting fields[pos] to a string, but the replace function doesn't work on it. I’m sure there is a good reason.
Why even bother trying to do some kind of replacement? Just assign it a new value:
obj.tracelog.fields[pos].atts[0]["name"] = newname;

String to Object

So basically I have this code:
var string = '{name: "bob", height: 4, weight: 145}';
I would like to know if it is possible to convert that string into an object.
so that I can use
string.name, string.height, and string.weight
(I am retrieving the string variable from a database so I cannot just remove the quotes and make it an object in the first place)
eval, as suggested by Igor, will certainly work but is vulnerable to attack.
Instead you could use a library to parse it for you. There are options in the following link:
Eval is evil... So what should I use instead?
It seems that your string is malformed. In order to work with JSON.parse or even jQuery.parseJSON methods, your keys must have speech marks (" ) around them, like so:
var str = '{"name": "bob", "height": 4, "weight": 145}';
var obj = JSON.parse(str);
You can test this by adding console.log(obj);​ as the final line. Here is my jsFiddle example.
So try to see if you can pull down the data from the server in the format I have suggested and it can then easily be parsed into a JavaScript object.
I would not use string for a variable name, but:
var obj = eval(string);
alert(obj.name);
or you can use jQuery.parseJSON: api.jquery.com/jQuery.parseJSON.

Categories