0

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"
}

2 Answers 2

1

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().

Sign up to request clarification or add additional context in comments.

1 Comment

JSON is always and only a string. Otherwise you have a JavaScript Object.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.