keshinpoint
keshinpoint

Reputation: 1001

Modify obtained JSON data

I recently was introduced to the world of APIs, and I'm trying to wrap my head around it a bit more, so thank you all in advance!

I have the following JSON data:

[
 {
"description": "Batman does.\n\nBatman vs. The Penguin (with Patton Oswalt)",
"updated_time": "2016-03-29T16:35:00+0000",
 }
]

Doing something like

var var1 = array.[0]description

will store var1 as the whole description.

I use Javascript (JQuery specifically). I want to get only the description before the \n\ i.e Batman does., and store it in a variable.

Upvotes: 2

Views: 64

Answers (3)

pillys
pillys

Reputation: 11

Try the code below,

var desc = (data[0].description.match(/[^\n]+/) || [''])[0];

Upvotes: -1

Tudor Constantin
Tudor Constantin

Reputation: 26861

Another way of achieving this is to substring() from 0 to the indexOf() \n:

var desc = data[0].description.substring(0, data[0].description.indexOf('\n') );

Although, the answer provided by Phil looks easier to read/understand for this case.

Upvotes: 1

Phil
Phil

Reputation: 164764

  1. Split on the newline and take the first array item, eg

    var desc = data[0].description.split('\n')[0];
    
  2. Parse the date string into a Date instance. Seeing as your string is ISO 8601 compliant, you can simply use the Date constructor...

    var d = new Date(data[0].updated_time);
    

    See formatting options here ~ https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date#Conversion_getter

Upvotes: 5

Related Questions