如何隔离我得到的JSON响应

时间:2017-07-19 06:17:50

标签: javascript angularjs json highcharts

Category = [TimeStamp1,TimeStamp2]

(其中TimeStamp1和TimeStamp2是有效时间戳)

我使用Rest Service获取上述数据。我需要 以不同的方式展示它。必须以这种方式转换它,我将在2个变量中得到响应,称为

Data=  [{
  name: 'DB',
  data: [100, 100]
}, {
  name: 'Oracle',
  data: [0, 100]
}] 

using DI_120_Interface.Class;
using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DI_120_Interface
{
    public partial class frmAddInventoryTransItem3 : MetroForm
    {
        public frmAddInventoryTrans ReceivingAdd { set; get; }
        public frmEditInventoryTrans ReceivingEdit { set; get; }

        string inv_type2 = null, action2 = null, document2 = null;
        static SerialPort _serialPort;
        static INIFile settings = new INIFile("C:\\Lateco\\settings.ini");
        private string weight;

        public frmAddInventoryTransItem3(object parent, string action, string inv_type, string document)
        {
            if (inv_type == "Receiving in LAVI" && action == "add")
                this.ReceivingAdd = (frmAddInventoryTrans)parent;
            else if (inv_type == "Receiving in LAVI" && action == "edit")
                this.ReceivingEdit = (frmEditInventoryTrans)parent;

            InitializeComponent();
            inv_type2 = inv_type;
            action2 = action;
            document2 = document;
        }

        private void frmAddInventoryTransItem3_Load(object sender, EventArgs e)
        {
            txtQty.Text = 1.ToString();
            txtWeight.Text = 0.ToString("N3");
            this.ActiveControl = txtPLU;

            string portname, baudrate, parity, databits, stopbits, handshake;

            portname = settings.Read("SERIAL PORT PROPERTIES", "PORT_NAME");
            baudrate = settings.Read("SERIAL PORT PROPERTIES", "BAUD_RATE");
            parity = settings.Read("SERIAL PORT PROPERTIES", "PARITY");
            databits = settings.Read("SERIAL PORT PROPERTIES", "DATA_BITS");
            stopbits = settings.Read("SERIAL PORT PROPERTIES", "STOP_BITS");
            handshake = settings.Read("SERIAL PORT PROPERTIES", "HANDSHAKE");

            _serialPort = new SerialPort(); //error here
            _serialPort.PortName = portname;
            _serialPort.BaudRate = int.Parse(baudrate);
            _serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity, true);
            _serialPort.DataBits = int.Parse(databits);
            _serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbits, true);
            _serialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake, true);

            _serialPort.Open();
            _serialPort.ReadTimeout = 200;
            if (_serialPort.IsOpen)
            {
                weight = "";
                txtWeight.Text = "000.000";
            }

            _serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                weight = _serialPort.ReadExisting();
                weight = weight.Substring(0, 7);

                try
                {
                    if (this.InvokeRequired)
                        this.BeginInvoke(new EventHandler(DisplayText));
                }
                catch (ObjectDisposedException) { }
            }
            catch (TimeoutException) { }
        }

        private void txtPLU_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                this.ActiveControl = txtQty;
            }
        }

        private void txtQty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                this.ActiveControl = txtWeight;
            }
        }

        private void txtWeight_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                this.ActiveControl = btnAddItem;
            }
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            string plu_code = txtPLU.Text;
            txtWarning.Text = "";

            if (IsNumeric(txtQty.Text) && IsNumeric(txtWeight.Text))
            {
                if (Convert.ToDecimal(txtQty.Text) == 0 || Convert.ToDecimal(txtWeight.Text) == 0)
                {
                    txtWarning.Text = "***Qty/Weight must not be equal to zero.***";
                    txtQty.Text = 1.ToString();
                    txtWeight.Text = 0.ToString("N3");
                    this.ActiveControl = txtQty;
                }
                else
                {
                    if (Functions.AddInventoryItemTempFromItemMasterUsingPLU(inv_type2, document2, plu_code, Convert.ToDecimal(txtQty.Text), Convert.ToDecimal(txtWeight.Text)))
                    {
                        txtPLU.Text = "";
                        txtQty.Text = 1.ToString();
                        txtWeight.Text = 0.ToString("N3");
                        this.ActiveControl = txtPLU;

                        if (inv_type2 == "Receiving in LAVI" && action2 == "add")
                            this.ReceivingAdd.UpdateQtyWeightAmount();
                        else if (inv_type2 == "Receiving in LAVI" && action2 == "edit")
                            this.ReceivingEdit.UpdateQtyWeightAmount();

                        //this.Close();
                    }
                    else
                    {
                        txtWarning.Text = "***PLU not found.***";
                        txtPLU.Text = "";
                        txtQty.Text = 1.ToString();
                        txtWeight.Text = 0.ToString("N3");
                        this.ActiveControl = txtPLU;
                    }
                }
            }
            else
            {
                txtWarning.Text = "***Please enter numeric value/s only.***";
                txtQty.Text = 1.ToString();
                txtWeight.Text = 0.ToString("N3");
                this.ActiveControl = txtQty;
            }
        }

        private bool IsNumeric(string s)
        {
            float output;
            return float.TryParse(s, out output);
        }

        private void DisplayText(object sender, EventArgs e)
        {
            txtWeight.Text = weight;
        }

        class INIFile
        {
            private string filePath;

            [DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

            public INIFile(string filePath)
            {
                this.filePath = filePath;
            }

            public void Write(string section, string key, string value)
            {
                WritePrivateProfileString(section, key, value, this.filePath);
            }

            public string Read(string section, string key)
            {
                StringBuilder SB = new StringBuilder(255);
                int i = GetPrivateProfileString(section, key, "", SB, 255, this.filePath);
                return SB.ToString();
            }

            public string FilePath
            {
                get { return this.filePath; }
                set { this.filePath = value; }
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_serialPort.IsOpen)
                _serialPort.Close();
        }   
    }
}

先谢谢

3 个答案:

答案 0 :(得分:1)

第一个很简单,只需将数据数组映射到只包含时间戳的数据并将其传输到Set

const Category = Array.from(new Set(obj.Data.map(datum => datum.TimeStamp)))

第二个将要求您将数据缩减为Rsrcstatus数组的地图,然后您可以将其转换为数组

const obj = {"Data":[{"Rsrc":"DB","status":"100","TimeStamp":"TimeStamp1"},{"Rsrc":"Oracle","status":"0","TimeStamp":"TimeStamp1"},{"Rsrc":"Oracle","status":"100","TimeStamp":"TimeStamp2"},{"Rsrc":"DB","status":"100","TimeStamp":"TimeStamp2"}]}

const Data = Array.from(obj.Data.reduce((map, datum) => {
  let data = map.get(datum.Rsrc) || []
  return map.set(datum.Rsrc, data.concat(datum.status))
}, new Map())).map(entry => ({
  name: entry[0],
  data: entry[1]
}))

console.info('Data', Data)

答案 1 :(得分:0)

我循环使用你的数据并构建了两个新数组。我使用第三个rsrc数组来帮助确定数据数组中的哪个位置也可以添加新项目。

var test = {
  "Data": [{
      "Rsrc": "DB",
      "status": "100",
      "TimeStamp": 'TimeStamp1'
    },
    {
      "Rsrc": "Oracle",
      "status": "0",
      "TimeStamp": 'TimeStamp1'
    },
    {
      "Rsrc": "Oracle",
      "status": "100",
      "TimeStamp": 'TimeStamp2'
    },
    {
      "Rsrc": "DB",
      "status": "100",
      "TimeStamp": 'TimeStamp2'
    }
  ]
};

var category = [];
var data = [];
var rsrc = [];

test['Data'].forEach(function( item ){
  
  if( category.indexOf( item['TimeStamp'] ) === -1 ){
    category.push( item['TimeStamp'] );
  }
  
  if( rsrc.indexOf( item[ 'Rsrc' ] ) === -1 ){
  	rsrc.push( item[ 'Rsrc' ] ); 
  }
  
  var pos = rsrc.indexOf( item[ 'Rsrc' ] );
  
  // set as itself or an object if it's not yet been set
  data[pos] = data[pos] || {};
  data[pos].name = item[ 'Rsrc' ];
  data[pos].data = data[pos].data || [];
  data[pos].data.push( item.status );

});

console.log( category );
console.log( data );

编辑修复了重复类别的问题,感谢@ yashgarg1232

答案 2 :(得分:0)



var input ={
  "Data": [{
      "Rsrc": "DB",
      "status": "100",
      "TimeStamp": "TimeStamp1"
    },
    {
      "Rsrc": "Oracle",
      "status": "0",
      "TimeStamp": "TimeStamp1"
    },
    {
      "Rsrc": "Oracle",
      "status": "100",
      "TimeStamp": "TimeStamp2"
    },
    {
      "Rsrc": "DB",
      "status": "100",
      "TimeStamp": "TimeStamp2"
    }
  ]
};
var data= input.Data;
var Category =[];
var Data =[];
var DataIndex = [];
data.forEach(function(i)
{
    if(Category.indexOf(i.TimeStamp)==-1) Category.push(i.TimeStamp);
    var idx=DataIndex.indexOf(i.Rsrc)
    if(idx==-1) {
        DataIndex.push(i.Rsrc);
        Data.push({name:i.Rsrc,data:[i.status]});
    } else {
         Data[idx].data.push(i.status);
    }
});

console.log(Category);
console.log(Data);