简体   繁体   English

从 reactjs 中的 json 对象获取值

[英]getting values from json objects in reactjs

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我已经在我的 sql 数据库中以 JSON 的形式存储了地址,我如何访问 object Z466DEEC76ECDF35FCA546 的每个键和值

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. billing_address 包含字段地址、国家、城市、state 和 zip。 How do I access each key and value inside billing_address JSON object in ReactJs?如何访问 ReactJs 中的 billing_address JSON object 中的每个键和值?

To get billing address you need to use JSON.parse .要获取帐单地址,您需要使用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 );

You can use JSON.parse() method to convert JSON string to object.您可以使用 JSON.parse() 方法将 JSON 字符串转换为 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM