If the CSV is only one line, JSON data with a different layout will be created.

Highlighted
Five Stars

If the CSV is only one line, JSON data with a different layout will be created.

Hi.

 

I have a CSV file that looks like this:

id,name,age
1,john,27
2,paul,30

I want to create JSON array like this:

[
    {"id":1,"name":"john","age":27},
    {"id":2,"name":"paul","age":30}
]

There is no problem if there are more than 2 rows in the CSV file.

 

But, if there is 1 line, it will be output like this.

Input:

id,name,age
1,john,27

Output:

{
    "dummyloop":{"id":1,"name":"john","age":27}
}

 

Why does the layout change?
I want the following results:

[{"id":1,"name":"john","age":27}]

 

I present a job with the minimum configuration that can reproduce this phenomenon.

(In fact, the job continues after this.)

Job OverviewJob OverviewtFileInputDelimitedtFileInputDelimitedtMaptMaptFileInputJSONField - ComponenttFileInputJSONField - ComponenttFileInputJSONField - SchematFileInputJSONField - SchematFileInputJSONField - JSON treetFileInputJSONField - JSON tree

 

Q:Why use a dummy loop?

A:The job continues after this.
This is the final layout:

{
  "app" : 9,
  "records" : [
    {"id":1,"name":"john","age":27},
    {"id":2,"name":"paul","age":30}
  ]
}

Thank you.

Highlighted
Community Manager

Re: If the CSV is only one line, JSON data with a different layout will be created.

Hi yanchi
If there is only one row, you need to add an attribute @class under dummyloop element, and set its value as "array", see image.

Snipaste_2019-11-19_15-57-20.png

It will generate a string like:

{"dummyloop":[{"id":"1","name":"john","age":"27"}]}

After that, you can remove other characters with this expression on a tJavaRow:

output_row.newColumn = input_row.newColumn.substring(input_row.newColumn.indexOf("["), input_row.newColumn.lastIndexOf("]")+1);

 

The result will be:

[{"id":"1","name":"john","age":"27"}]

 

Regards

Shong

----------------------------------------------------------
Talend | Data Agility for Modern Business

2019 GARTNER MAGIC QUADRANT FOR DATA INTEGRATION TOOL

Talend named a Leader.

Get your copy

OPEN STUDIO FOR DATA INTEGRATION

Kickstart your first data integration and ETL projects.

Download now

Best Practices for Using Context Variables with Talend – Part 2

Part 2 of a series on Context Variables

Blog

Best Practices for Using Context Variables with Talend – Part 1

Learn how to do cool things with Context Variables

Blog

Migrate Data from one Database to another with one Job using the Dynamic Schema

Find out how to migrate from one database to another using the Dynamic schema

Blog