0

What is the best method utilizing javascript to parse this JSON response:

{
    "records":[{
         "id":"recV4gf3nPUzO980w",
         "fields":{
            "truck name":"Darla's dumpling cart",
            "address":"150 W 57th St, New York, NY"
         },
         "createdTime":"2018-04-27T22:48:13.000Z"
    }]
} 

So that only the "fields" data is returned, This is a representation of only one record in records and I need to create obj.records.fields where all fields are presented as an array.

Chuck LaPress
  • 278
  • 1
  • 10
  • 18
  • 2
    `obj.records[0].fields` – CertainPerformance Apr 29 '18 at 02:06
  • I think it's important to be clear here that since this is already a JavaScript Object (at least in the code you posted), there's no need for parsing, just simple property access as @CertainPerformance demonstrated. If that entire code was a String type, then you'd need to use `JSON.parse(rawJsonString)` to make your object and then use property access. – benmccallum Apr 29 '18 at 02:23
  • Might be best to clear up what you've got by editing your question to either: `var obj = { ... }` or `var jsonString = "{ ... }"`. – benmccallum Apr 29 '18 at 02:24
  • You should also clarify if the array `records` will have more than one value. Do you want an array of the 'fields' objects or will there always only be one? – Mark Apr 29 '18 at 02:28
  • To answer Mark, yes records will be more then one, so data obj could be 10 records all structured the same way and I will need to loop through each for fields so obj.records[0].fields does give me the first field but obj.records[3].fields gives me the fourth listing I would like to have all fields as an array – Chuck LaPress Apr 29 '18 at 16:18

3 Answers3

2

You have to parse response Json, then find the value as

var obj = JSON.parse(response);
var fields=obj.records[0].fields;
Mesar ali
  • 1,832
  • 2
  • 16
  • 18
1

The JSON.parse reviver parameter can be used to get specific value:

var fields, j = `{ "records":[{ "id":"recV4gf3nPUzO980w", "fields":{ "truck name":"Darla's dumpling cart", "address":"150 W 57th St, New York, NY" }, "createdTime":"2018-04-27T22:48:13.000Z" }] }`

JSON.parse(j, (key, value) => key === 'fields' ? (fields = value) : value)

console.log( fields )
Slai
  • 22,144
  • 5
  • 45
  • 53
0

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Make sure the text is written in JSON format, or else you will get a syntax error.

Mark
  • 90,562
  • 7
  • 108
  • 148
Srinivas GV
  • 167
  • 7