连接两个主键关联的2个JSON输入

2024-03-28 20:09:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从以下内容合并2个JSON输入(本例来自一个文件,但稍后将来自一个Google Pub子输入):

orderID.json:    
{"orderID":"test1","orderPacked":"Yes","orderSubmitted":"Yes","orderVerified":"Yes","stage":1}



combined.json:
    {"barcode":"95590","name":"Ash","quantity":6,"orderID":"test1"}
    {"barcode":"95591","name":"Beat","quantity":6,"orderID":"test1"}
    {"barcode":"95592","name":"Cat","quantity":6,"orderID":"test1"}
    {"barcode":"95593","name":"Dog","quantity":6,"orderID":"test2"}
    {"barcode":"95594","name":"Scar","quantity":6,"orderID":"test2"}

类似这样的操作(使用orderID作为唯一主键):

output.json: 
{"orderID":"test1","orderPacked":"Yes","orderSubmitted":"Yes","orderVerified":"Yes","stage":1,"barcode":"95590","name":"Ash","quantity":6}
{"orderID":"test1","orderPacked":"Yes","orderSubmitted":"Yes","orderVerified":"Yes","stage":1,"barcode":"95591","name":"Beat","quantity":6}
{"orderID":"test1","orderPacked":"Yes","orderSubmitted":"Yes","orderVerified":"Yes","stage":1,"barcode":"95592","name":"Cat","quantity":6}

我现在有这样的代码,是从join two json in Google Cloud Platform with dataflow改编的

from __future__ import absolute_import
import argparse
import apache_beam as beam
import json
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
from apache_beam.options.pipeline_options import StandardOptions
from google.api_core import datetime_helpers
from google.api_core.exceptions import InternalServerError
from google.api_core.exceptions import ServiceUnavailable
from google.api_core.exceptions import TooManyRequests
from google.cloud import bigquery

def run(argv=None):
    """Build and run the pipeline."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--topic',
        type=str,
        help='Pub/Sub topic to read from')
    parser.add_argument(
        '--topic2',
        type=str,
        help='Pub/Sub topic to match with'
    )
    parser.add_argument(
        '--output',
        help=('Output local filename'))

    args, pipeline_args = parser.parse_known_args(argv)
    options = PipelineOptions(pipeline_args)
    options.view_as(SetupOptions).save_main_session = True
    options.view_as(StandardOptions).streaming = True

p = beam.Pipeline(options=options)

    orderID = (p | 'read from text1' >> beam.io.ReadFromText('orderID.json') 
    #'Read from orderID PubSub' >> beam.io.ReadFromPubSub(topic=args.topic2)
                | 'Parse JSON to Dict' >> beam.Map(lambda e: json.loads(e))
                | 'key_orderID' >> beam.Map(lambda orders: (orders['orderID'], orders))
                )

    orders_si = beam.pvalue.AsDict(orderID) 

    orderDetails = (p | 'read from text' >> beam.io.ReadFromText('combined.json') 
                      | 'Parse JSON to Dict1' >> beam.Map(lambda e: json.loads(e)))
    #'Read from PubSub' >> beam.io.ReadFromPubSub(topic=args.topic))

    def join_orderID_orderDetails(order, order_dict):
        return order.update(order_dict[order['orderID']])

    joined_dicts = orderDetails | beam.Map(join_orderID_orderDetails, order_dict=orders_si)

    joined_dicts | beam.io.WriteToText('beam.output')

p.run()
#result.wait_until_finish()

if __name__ == '__main__':
    run()

但我现在的产出光束输出仅显示:

None
None
None

有人能告诉我我做错了什么吗?你知道吗

与报告的重复职位不同的问题是:

  1. 为什么我的结果是“无”?你知道吗
  2. 我做错什么了?你知道吗
  3. 我怀疑这些是问题:

    • “order”变量-在“join\u orderID\u orderDetails”中引用是否正确
    • “join\u dicts”中的列表项“join\u orderID\u orderDetails”?-这也正确吗?你知道吗

Tags: namefromimportjsontopicpipelineorderbarcode
1条回答
网友
1楼 · 发布于 2024-03-28 20:09:52

试试下面的,希望能对你有所帮助。你知道吗

在这里,我使用了一个数组的顺序和组合,而不是使用一个文件。你知道吗

order = [{"orderID":"test1","orderPacked":"Yes","orderSubmitted":"Yes","orderVerified":"Yes","stage":1}]

combined = [
   {"barcode":"95590","name":"Ash","quantity":6,"orderID":"test1"},
   {"barcode":"95591","name":"Beat","quantity":6,"orderID":"test1"},
   {"barcode":"95592","name":"Cat","quantity":6,"orderID":"test1"},
   {"barcode":"95593","name":"Dog","quantity":6,"orderID":"test2"},
   {"barcode":"95594","name":"Scar","quantity":6,"orderID":"test2"}
   ]


def joinjson(repl, tobeCombined):
  newarr = []
  for data in tobeCombined:
    replData = getOrderData(repl,data['orderID'])
    if replData is not None:
      data.update(replData)
    newarr.append(data)

  return newarr

def getOrderData(order, orderID):
  for data in order:
    print("Data OrderID : ",data['orderID'])
    if data['orderID'] == orderID:
      return data



print(joinjson(order,combined))

相关问题 更多 >