如何从一个字符串对象中获取值?

时间:2019-11-19 09:13:57

标签: javascript javascript-objects

"{"OrderId":XXXXXX,"IsPrebuy":true,"IsReserve":false,"Date":"2019-11-19","ReservationFee":0,"MovieTitle":"Joker"}"

这是购买后输入标签中的值。如何获得“电影标题”的值? 如您所见,一切都在“”之内。

当我尝试这样做时:

var products = "{"OrderId":XXXXXX,"IsPrebuy":true,"IsReserve":false,"Date":"2019-11-19","ReservationFee":0,"MovieTitle":"Joker"}"

然后我尝试了这个:

    (Object.values(products))
(556) ["{", """, "O", "r", "d", "e", "r", "I", "d", """, ":", "9", "9", "3", "9", "1", "1", ",", """, "I", "s", "P", "r", "e", "b", "u", "y", """, ":", "t", "r", "u", "e", ",", """, "I", "s", "R", "e", "s", "e", "r", "v", "e", """, ":", "f", "a", "l", "s", "e", ",", """, "D", "a", "t", "e", """, ":", """, "2", "0", "1", "9", "-", "1", "1", "-", "1", "9", """, ",", """, "R", "e", "s", "e", "r", "v", "a", "t", "i", "o", "n", "F", "e", "e", """, ":", "0", ",", """, "M", "o", "v", "i", "e", "T", "i", "t", …]

我不知道下一步是什么?

2 个答案:

答案 0 :(得分:0)

如果它是JSON字符串,则需要先对其进行解析:

// raw text from input-tag
const text = `{"OrderId":XXXXXX,"IsPrebuy":true,"IsReserve":false,"Date":"2019-11-19","ReservationFee":0,"MovieTitle":"Joker"}`;

// parse it to a javascript object
const products = JSON.parse(text);

// get the value
const title = products.MovieTitle;

答案 1 :(得分:0)

您的数据采用JSON形式。因此,将字符串解析为JSON对象。

var products = JSON.parse('{"OrderId":"XXXXXX","IsPrebuy":true,"IsReserve":false,"Date":"2019-11-19","ReservationFee":0,"MovieTitle":"Joker"}')

然后从JSON对象获取movieTitle值,

products.MovieTitle;

注意:如果您的订单ID的类型为字符串,则必须用双引号引起来。