Add a field to a JSON object in javascript - javascript

How do you add a field to a json in javascript?
I've seen it done with arrays but I need it with a JSON field.
So basically
{
"hello":"this is cool"
}
into
{
"hello":"this is cool",
"hi":"i know"
}

You can do it like so
const json = {
"hello":"this is cool"
};
json['hi'] = "i know";
console.log(json);
If JSON is a string you can use JSON.parse() as per MDN web docs JSON.parse().

If you want to do it to JSON, then you can do it like below.
let json = `{
"key": "value"
}`;
const obj = JSON.parse(json);
obj.website = "Stack Overflow";
json = JSON.stringify(obj);
console.log(json);
However, if you want to do it to a regular object, just simply run the code below.
const obj = {
key: "value",
};
obj.website = "Stack Overflow";
console.log(obj);

Related

Can I change a JSON key from string value to an array of value in JS

Hi I would like to check if there's a way to convert one of my JSON property's value from string to an array of string.
What I have:
const testJSON = {
"name": "Albert"
}
What I want:
const testJSON = {
"name": ["Albert"]
}
Many thanks for any help and direction I could explore!
You can give a try to this dynamic solution with the help of Object.keys() and Array.forEach() method.
const testJSON = {
"name": "Albert"
};
Object.keys(testJSON).forEach(key => {
testJSON[key] = [testJSON[key]]
});
console.log(testJSON);
You can assign new value which can be string or array to json property.
For example:
const testJSON = {
"name": "Albert"
}
// new array which we will assign to previous array property
const newArray = ["Albert", "John"];
// assigning new array to old json property
testJSON.name = newArray;
Don't think so, you only do maybe like the comment above
{name: [testJSON.name]}
if you have array, u can do .map for it

convert string to object from html input element

I have a textarea element which takes object types as an input
like
{
name: "root",
backlog: [
{name: "log#1"},
]
}
Accessing the data returns it as a string
Is there a simple way to convert the String to that specific javascript object without using regex filters? Just removing the outer quotation marks?
use json5 or Relaxed JSON library.
here is example using json5 library
let string = ` {
name: "root",
backlog: [
{name: "log#1"},
]
}`;
let object = JSON5.parse(string);
console.log(object)
<script src="https://unpkg.com/json5#^2.0.0/dist/index.min.js"></script>
To convert a string to a JSON, use: JSON.parse([the input]).
And, to convert it back to a string: JSON.stringify([the input]).
If i understand you correctly :
const string = '{ name: "root", backlog: [{name: "log#1"}]}'
const jsonStr = string.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';
});
const result = JSON.parse(jsonStr)
console.log(result)
If you want to use a simple, native approach you could simply stringify and then parse it using the intrinsic JSON object, i.e. something like this:
let yourObject = JSON.parse(JSON.stringify(textareaVariable));
This works because stringify will essentially format the string into a JSON string with the appropriate syntax for a JSON document, which you can then parse into a standard object.
Convert a JavaScript object into a string with JSON.stringify().
Create a JSON string from a JavaScript object.
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
console.log(myJSON);
//Output: {"name":"John","age":30,"city":"New York"}
Parse the data with JSON.parse(), and the data becomes a JavaScript object.
Creating an Object from a JSON String
const txt = {"name":"John", "age":30, "city":"New York"}
const obj = JSON.parse(txt);
console.log(obj.name + ", " + obj.age);
//Output:John, 30
You can simply use a JSON.parse call with some parameters to maintain the indetation.
const text = '{"firstName":"John", "lastName":"Doe", "address":{"city": "Tanger", "country": "Morocco"}}';
const obj = JSON.stringify(JSON.parse(text), null, 2)
console.log(obj);

Search into a json file a value with only javascript and fs

i want to create a javascript function for search into a json file a object with the value.
getByValue(value) {
//the code
}
When i call the function, i need to search into a json file (the path is "./database/table.json") what i passed with value parameter, and return the object name.
An example:
JSON file:
{"name": "test"}
getByValue(value) {
//code for search into the file
}
//search on the json file a object value with "test"
console.log(getByValue("test"))
//expected output: "name"
You can do something like this :
const json = { "name": "test" , "name1" : "test1"}
const getByValue = value => {
for (let key of Object.keys(json)) if (json[key] === value) return key;
}
//search on the json file a object value with "test"
console.log(getByValue("test"))
//expected output: "name"
You need to first load that JSON in JS environment and parse it to read. In node.js you can do something like this
const jsonFromFile = require('filepath/file.json')
After reading the JSON, you just need to find the key where the value is given. There are multiple approaches to this. The basic solution is need to iterate over the object and find the value which matches.
One such approach:
const findKeyBasedOnValue = (obj, value) => Object.keys(obj).find((key) => obj[key] === value)
const data = {a: 'no-test', b: 'test'}
console.log(findKeyBasedOnValue(data, 'test')) // b

How can i remove a property from an object but keep its values?

I would like to know how can I remove the "formvalue1" property from the following object but keep its children.
{
"formvalue1": {
"title": "sdf",
"tname": "sdff",
"taddress": "dfsdf"
}
}
Try reassigning the object:
let obj = {"formvalue1": { "title":"sdf", "tname":"sdff", "taddress":"dfsdf" } };
obj = obj.formvalue1;
console.log(obj)
If the original JSON is a string and not a JSON object. In javascript you can use JSON.parse to parse the string into an object literal (see comment below pointing out the discrepancy).
const jsonStr = '{"formvalue1": {"title": "sdf", "tname": "sdff", "taddress": "dfsdf"}}'
let obj = JSON.parse(jsonStr);
obj = obj.formvalue1;
console.log(obj)
you use some destructuring
const d = {
"formvalue1": {
"title": "sdssssssf",
"tname": "sdff",
"taddress": "dfsdf"
}
}
const {
formvalue1
} = d
const nd = formvalue1
console.log(nd)

Parse a string into object?(JavaScript)

Would it be possible to parse a string as follows… {"Key": "Value"} back into a object? When I ever I try to parse it, I receive errors. I've been trying to use json.parse, but that does not work either.
This is what i have mapped out, but for this format it fails.
// Creating a list of objects, while mapping properties of an object
let obj = "{
"key": "3"
}";
let objList = Object.entries(obj).map(([key, value]) => Object.fromEntries(new Map([
[key, value]
])));
let obj = "{
"key": "3"
}";
This is incorrect: if you want to write a multiline string, you have to put a \ at the end of the line:
let obj = "{\
"key": "3"\
}";
But there is another error: you have to escape the ":
let obj ="{\
\"key\": \"3\"\
}";
You could use ' for enclosing string instead of " so you don't need the escape:
let obj = '{\
"key": "3"\
}';
Anyway this is a little string, you could write it in one line:
let obj = '{"key": "3"}';
Now you can use JSON.parse.
let obj = '{"key": "3"}';
console.log( JSON.parse(obj) );

Categories

Resources