在NodeJS中解析JSON

时间:2017-03-03 12:56:17

标签: json node.js rest api request

我正在尝试使用简单的NodeJS HTTP服务器从远程API获取JSON(它使用request进行HTTP调用)。当我通过一些JSON验证器运行HTTP响应时,它说它是一个有效的JSON,但是我无法管理访问密钥甚至是数组等的密钥。

JSON看起来像:

{
    "submissions": [{
        "token": "db7fa11f970f376cc17c5f8d1760ab98",
        "created_at": "2017-03-02T13:01:35Z",
        "saved_at": "2017-03-02T12:50:35Z",
        "changed_at": "2017-03-02T12:50:35Z",
        "email": "",
        "data": {
            "CompName": "",
            "Name": "TestFirma01",
            "MA_Name": "Robert Dotzlaff",
            "CASFunction": "TestFunktion01",
            "CreateDate": "02.03.2017",
            "Street1": "TestStrasse",
            "Zip1": "12345",
            "Town1": "Berlin",
            "PhoneFieldStr4": "07225919241",
            "MailFieldStr1": "tes@mpl.de",
            "Category1": [
                "CRM"
            ],
            "Category2": [
                "mpl Finance"
            ],
            "gwBranch": [
                "B2B",
                "B2C"
            ],
            "ITDANZAHLMA": "<25",
            "MPLUSERPOT": "<5",
            "TurnOver": "<50.000",
            "gwBranch_Product": "Maschinen",
            "gwBranch_Solution": "Keine",
            "Konkurenz": "Nein",
            "MPLEINFUEHRUNG1": null,
            "MPLEINFUEHRUNG2": [
                "> 12 Monate"
            ],
            "MPLEINFUEHRUNG3": "02.03.2017",
            "MPLINFRASTRUKTUR1": [
                "ERP"
            ],
            "MPLINFRASTRUKTUR2": [
                "Lotus"
            ],
            "MPLINFRASTRUKTUR3": [
                "RDP-Anbindung"
            ],
            "MPLINTTHEMA1": [
                "Projektmanagement",
                "Vertrieb"
            ],
            "MPLINTTHEMA2": [
                "Auswertungen",
                "Zeiterfassung"
            ],
            "MPLINTTHEMA3": [
                "Sonstiges"
            ],
            "MPLSONSTIGEINFOS": "Es muss schnell sein",
            "MPLKONKPRODUKT": "",
            "ANSPR_TEAM": "Robert D",
            "ANSPR_Entscheider": "Ptrick R",
            "MPLENTSCHEIDUNG": "02.03.2017",
            "ITDKLASSIFIZIERUNG": [
                "sehr gut"
            ],
            "NEXT_ACTION": [
                "Testzugang"
            ]
        },
        "attachments": []
    }]
}

NodeJS脚本如下:

'use strict'

const Hapi = require('hapi');
const Express = require('express');
const Request = require('request');
const Vision = require('vision');
const Handlebars = require('handlebars');
const _ = require('lodash');
const LodashFilter = require('lodash.filter');
const LodashTake = require('lodash.take');
const JSONStream = require('JSONStream');
const jQuery = require('jsdom');

const server = new Hapi.Server();

server.connection({
    host: '127.0.0.1',
    port: 3000,
    routes: {
        cors: {
            origin: ['*'],
            additionalHeaders: ['X-API-KEY']
        },

    }
});

server.register(Vision, (err) => {
    server.views({
        engines: {
            html: Handlebars
        },
        relativeTo: __dirname,
        path: './views',
    });
});

server.start((err) => {
    if (err) {
        throw err;
    }
    getJSON();
    console.log(`Server running at: ${server.info.uri}`);
});

function getJSON() {

    // URL and APIKEY ommitted for security reasons
    var as_host = '';
    var as_apiKey = ''
    var as_endpoint = '/api/public/v1/projects/';
    var as_projectId = '736';
    var as_endpointExt = '/submissions';
    var as_url = as_host + as_endpoint + as_projectId + as_endpointExt;

    var options = {
        url: as_url,
        headers: {
            'X-API-KEY': as_apiKey,

        },
        json: true
    };

    function callback(error, response, body) {
        if (!error && response.statusCode == 200) {         
            var jsonString1 = JSON.stringify(body);
            var jsonObject = JSON.parse(jsonString1);


            console.log("BODY2: " + jsonObject);

        }
    }
    Request(options, callback);
}

console.log("BODY2: " + jsonObject);输出BODY2: [object Object]这不是我想要的。当我从json: true的options变量中删除request时,它会输出JSON(或至少看起来像一个),但我仍然无法访问JSON中的键/值对。我需要特别访问JSON的data部分,其中包含需要切换到第二个远程REST API的相关数据集(只接受特殊格式,这就是为什么我不能简单地处理检索到的JSON到其他API)。我已经尝试了几个解决方案并在这里阅读了很多帖子,它们似乎都不适用于我(JSON.parse()JSONStream.parse()_.get()等等。非常感谢任何帮助!

0 个答案:

没有答案