-1

I have an Output in JSON like this. I now have to use this data for the regression line fitting.

[{"year":"1995","values":"46.8550182"},{"year":"1996","values":"47.1409752"},                   {"year":"1997","values":"46.6331669"},{"year":"1998","values":"46.3054604"]

Initially, I did this small project with the data inside the same module which was like this.

var data = [

            [1995, 46.85],
            [1996, 47.14],
            [1997, 46.63],
            [1998, 46.31],
            [1999, 45.50],
            [2000, 46.09],] 

Now I want to take data from the JSON file and use that data for the regression line fitting. How can I do that ? Would you please help me ?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Shiva Bhusal
  • 57
  • 10
  • 1
    look at [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) for starters. – The Paramagnetic Croissant Aug 10 '14 at 15:35
  • duplicate question here http://stackoverflow.com/questions/20881213/converting-json-object-into-javascript-array – limbenjamin Aug 10 '14 at 15:38
  • @ Limbenjamin, I tried the first answer on the top but it too didn't work for me. – Shiva Bhusal Aug 10 '14 at 16:10
  • What exactly are you having problems with? Parsing the JSON? Iterating over an array? Accessing properties of an object? Creating a new array? Adding elements to an array? Something else? Those are all really basic things. If you read the MDN javascript guide, you will learn about these things: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide – Felix Kling Aug 10 '14 at 16:17
  • I'm having problem creating a new array. I want to create a new array like just like the second one ( var data =[[1995, 46.85], [1996, 47.14]) from the data in JSON format. – Shiva Bhusal Aug 10 '14 at 16:19
  • Creating a new array is as simple as `var newArray = [];`. Then you can add elements with `newArray.push(value);`. FYI, the steps I listed above is one way to convert the input array into the output array. So if you know all of things, you should be able to achieve your goal following those steps. – Felix Kling Aug 10 '14 at 16:22

1 Answers1

1

Will this work for you?

http://jsfiddle.net/qkox62z5/

Uses map and assumes data is coming in as an array already so youd need to use JSON.parse on the json string from where it comes from

function format( jsonData ){
    return jsonData.map( function( item ){ return[ item.year, item.values] });
}

Usage is like...

format( JSON.parse( jsonString ) ) // where jsonString is your response from the json file
Scott Mitchell
  • 698
  • 4
  • 11