Converting cvs string to json string

csv_string = “ITEM_NAME,DESTINATION_ORG_CODE,UOM_CODE,QUANTITY,WORK_ORDER_START_DATE,WORK_ORDER_COMPLETION_DATE,SUPPLY_OPERATION,WORK_ORDER_NUMBER,WORK_DEFINITION_CODE,WORK_METHOD_CODE_VAL,“FIRM_PLANNED_FLAG”
101512-01,1210,ea,264,2020-05-11,2020-06-12,CREATE,3443039,PRIMARY,DISCRETE_MANUFACTURING,2”
how can i convertthis to json string?

Hi :wave:

You can do it this way:

Code

head=  <<~HEAD
	ITEM_NAME,DESTINATION_ORG_CODE,UOM_CODE,QUANTITY,WORK_ORDER_START_DATE,WORK_ORDER_COMPLETION_DATE,SUPPLY_OPERATION,WORK_ORDER_NUMBER,WORK_DEFINITION_CODE,WORK_METHOD_CODE_VAL,"FIRM_PLANNED_FLAG"
HEAD

values = [
	"101512-01,  1210,ea,264,2020-05-11,2020-06-12,CREATE,3443039,PRIMARY,DISCRETE_MANUFACTURING,2",
	"1111110-01,1211,ea,264,2020-04-11,2020-06-12,CREATE,3443039,PRIMARY,DISCRETE_MANUFACTURING,3"
]
head_splitted = head.split( ?, ).each( &:strip! )

require 'json'
to_json = JSON.pretty_generate(
	values.map.with_index do |x, i|
		{ i.next => head_splitted.zip( x.split( ?, ).each( &:strip! ) ).to_h }
	end
)

puts to_json

Now being ignorant to the data, I have added one dummy data in the values array just to show you that you can just push strings to the array to add it to the JSON…

Instead of JSON.pretty_generate, which generates readable JSON, if you care about performance, you can also generate the minified version, which can be done by method-chaining to_json the values.map... here.

Output

[
  {
    "1": {
      "ITEM_NAME": "101512-01",
      "DESTINATION_ORG_CODE": "1210",
      "UOM_CODE": "ea",
      "QUANTITY": "264",
      "WORK_ORDER_START_DATE": "2020-05-11",
      "WORK_ORDER_COMPLETION_DATE": "2020-06-12",
      "SUPPLY_OPERATION": "CREATE",
      "WORK_ORDER_NUMBER": "3443039",
      "WORK_DEFINITION_CODE": "PRIMARY",
      "WORK_METHOD_CODE_VAL": "DISCRETE_MANUFACTURING",
      "\"FIRM_PLANNED_FLAG\"": "2"
    }
  },
  {
    "2": {
      "ITEM_NAME": "1111110-01",
      "DESTINATION_ORG_CODE": "1211",
      "UOM_CODE": "ea",
      "QUANTITY": "264",
      "WORK_ORDER_START_DATE": "2020-04-11",
      "WORK_ORDER_COMPLETION_DATE": "2020-06-12",
      "SUPPLY_OPERATION": "CREATE",
      "WORK_ORDER_NUMBER": "3443039",
      "WORK_DEFINITION_CODE": "PRIMARY",
      "WORK_METHOD_CODE_VAL": "DISCRETE_MANUFACTURING",
      "\"FIRM_PLANNED_FLAG\"": "3"
    }
  }
]

Hope this helps!

1 Like

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs