1

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: "xxx@gmail.com",
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?

Phil
  • 157,677
  • 23
  • 242
  • 245
Angelin
  • 95
  • 1
  • 9
  • 1
    Please check [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) and [JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) – kiranvj Jun 02 '21 at 04:22
  • @kiranvj the question you referred to doesn't answer Angelin's question. They need help with JSON.parse instead. – Christian Fritz Jun 02 '21 at 04:28
  • @ChristianFritz Sure. Voted to reopen. – kiranvj Jun 02 '21 at 04: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 – Phil Jun 02 '21 at 04:53
  • @Phil thanks a lot! – Angelin Jun 02 '21 at 05:15

2 Answers2

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: "xxx@gmail.com",
name: "xxx"
};

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

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

console.log("Country:", billingAddress.country );
kiranvj
  • 32,342
  • 7
  • 71
  • 76
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: "xxx@gmail.com",
 name: "xxx"
};

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

console.log(address);
console.log(address.billing_address.country);
Nirav Vikani
  • 118
  • 8