简体   繁体   English

将 JSON 文件发送到 Azure 事件中心

[英]Sending JSON File to Azure Event Hub

I wish to send a JSON file to Azure event hub using the sample code given in Microsoft website.我希望使用 Microsoft 网站中提供的示例代码将 JSON 文件发送到 Azure 事件中心。 The code looks to be incorrect and not seeing the below uploaded file in event hub.代码看起来不正确,在事件中心看不到下面上传的文件。

Could someone help on how to send the actual JSON file?有人可以帮助发送实际的 JSON 文件吗?

import asyncio

from azure.eventhub import EventData
from azure.eventhub.aio import EventHubProducerClient


async def run():
    producer = EventHubProducerClient.from_connection_string(
        conn_str="foo",
        eventhub_name="boo")
    async with producer:
        event_data_batch = await producer.create_batch()
        event_data_batch.add(EventData(JSONFilepath))
        await producer.send_batch(event_data_batch)


loop = asyncio.get_event_loop()
loop.run_until_complete(run())

Note: I am not facing error while running the program.注意:我在运行程序时没有遇到错误。

A code snippet to send JSON Objects & JSON String to event Hub将 JSON 对象和 JSON 字符串发送到事件中心的代码片段

import asyncio
import nest_asyncio
nest_asyncio.apply()
from azure.eventhub.aio import EventHubProducerClient
from azure.eventhub import EventData
import json

async def run():
    # Create a producer client to send messages to the event hub.
    # Specify a connection string to your event hubs namespace and
        # the event hub name.
    producer = EventHubProducerClient.from_connection_string("<>", eventhub_name="<>")
    async with producer:
        # Create a batch.
        event_data_batch = await producer.create_batch()

        # Add events to the batch.

        #Method 1 - You provide a JSON string 
        body1 = '{"id":"device2","timestamp":"2016-01-17T01:17:00Z"}' 
        event_data_batch.add(EventData(body1))

        #Method 2 - You get the JSON Object and convert to string
        json_obj = {"id":"device3","timestamp":"2016-01-18T01:17:00Z"}
        body2= json.dumps(json_obj)
        event_data_batch.add(EventData(body2))


        #This just sending the string which will not be captured by TSI
        event_data_batch.add(EventData('Third event'))

        # Send the batch of events to the event hub.
        await producer.send_batch(event_data_batch)


loop = asyncio.get_event_loop()
loop.run_until_complete(run())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM