2

I have stored the address in the form of JSON in my sql database, how do I access each key and value of the object json

Users Table values:

{
id: 1, 
billing_address: "\"{\\\"country\\\":\\\"India\\\",\\\"address\\\":\\\"23, 4th cross\\\",\\\"city\\\":\\\"Udupi\\\",\\\"state\\\":\\\"Tamil Nadu\\\",\\\"zip\\\":\\\"123456\\\"}\"",
created_at: "2021-06-02T03:16:04.000Z",
email: "[email protected]",
name: "xxx"
}

The billing_address has the fields address, country, city, state and zip. How do I access each key and value inside billing_address JSON object in ReactJs?

5
  • 1
    Please check Object.entries and JSON.parse Commented Jun 2, 2021 at 4:22
  • @kiranvj the question you referred to doesn't answer Angelin's question. They need help with JSON.parse instead. Commented Jun 2, 2021 at 4:28
  • @ChristianFritz Sure. Voted to reopen. Commented Jun 2, 2021 at 4:49
  • You've got a double-encoded JSON string. To parse it, use JSON.parse(JSON.parse(obj.billing_address)). The better option would be to fix whatever is double-encoding it Commented Jun 2, 2021 at 4:53
  • @Phil thanks a lot! Commented Jun 2, 2021 at 5:15

2 Answers 2

2

To get billing address you need to use JSON.parse . With your current data format you need to use it twice. Please see below code.

var data = {
id: 1, 
billing_address: "\"{\\\"country\\\":\\\"India\\\",\\\"address\\\":\\\"23, 4th cross\\\",\\\"city\\\":\\\"Udupi\\\",\\\"state\\\":\\\"Tamil Nadu\\\",\\\"zip\\\":\\\"123456\\\"}\"",
created_at: "2021-06-02T03:16:04.000Z",
email: "[email protected]",
name: "xxx"
};

var billingAddress = JSON.parse(JSON.parse(data.billing_address));

console.log("Billing address:", billingAddress);

console.log("Country:", billingAddress.country );

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

Comments

1

You can use JSON.parse() method to convert JSON string to object.

For example:

const dbAddress = 
{
 id: 1, 
 billing_address: "\"{\\\"country\\\":\\\"India\\\",\\\"address\\\":\\\"23, 4th cross\\\",\\\"city\\\":\\\"Udupi\\\",\\\"state\\\":\\\"Tamil Nadu\\\",\\\"zip\\\":\\\"123456\\\"}\"",
 created_at: "2021-06-02T03:16:04.000Z",
 email: "[email protected]",
 name: "xxx"
};

const address = 
{
  ...dbAddress,
  billing_address: JSON.parse(JSON.parse(dbAddress.billing_address)),
};

console.log(address);
console.log(address.billing_address.country);

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.