简体   繁体   English

带有JSON数据的jQuery条件

[英]jQuery conditionals with JSON data

I have some JSON data where there is a field like such: 我有一些JSON数据,其中有一个像这样的字段:

"first_date": "2015-06-02"

In jQuery, I'm wanting to basically say something like this: 在jQuery中,我基本上想说这样的话:

if( valueOfFirstDate.substring(5, 6) == "06" ){
    //change 06 to "June"
}

How would I go about grabbing the value of that first_date field? 我将如何获取该first_date字段的值?

You could use JSON.parse() to convert your string to an object 您可以使用JSON.parse()将字符串转换为对象

var json = '{"first_date": "2015-06-02"}';
var obj = JSON.parse(json);
if(obj.first_date.substring(5, 6) == "06" ){
...
}

Just write something like that: 就像这样写:

JsonObject.first_date

That's it. 而已。 here your JsonObject is just any object of JavaScript. 在这里,您的JsonObject只是JavaScript的任何对象。

You could generalize this for all months: 您可以将其推广到所有月份:

 var obj = { "first_date": "2015-06-02" }, d = obj['first_date'].split('-'), months = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']; obj['first_date'] = d[0] + '-' + months[ +d[1] ] + '-' + d[2]; alert( JSON.stringify(obj, null, 4) ); 

You don't need jQuery for this. 您不需要jQuery。 Plain old javascript will work. 普通的旧javascript即可使用。

If you're given a json object then you can access the value with the key. 如果为您提供json对象,则可以使用键访问值。

var obj = {
  "first_date" : "2015-06-02"
}

if (obj["first_date"].substring(5, 6) == "06") {
  //your code here
}

I would recommend that if you want to work with dates to use objects instead. 我建议如果您要使用日期来代替使用对象。 It's always better to work with objects rather than strings. 使用对象而不是字符串总是更好。 You can form a javascript object from a date string as well. 您也可以根据日期字符串形成javascript对象。 Check out Mozilla Dev Documentation Here 在此处查看Mozilla Dev文档

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

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