使用基于fixedposition的模式将原始字符串数据转换为基于对象的结构,如JSON

2024-10-01 02:36:28 发布

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

我的用例如下:

输入格式-具有固定总长度和每组固定位置的字符串表示某个值

让输入为{{CD1}},并考虑位置1到3 ^ {}将表示字段1值,位置4到7 ^ { CD3>}将表示字段2值,位置8到10 ^ ^ {CD4>}将表示字段3值

输出格式-基于对象的结构,如JSON

{
"field1" : "ABC",
"field2" : "DE12",
"field3" : "345"
}

我的要求按优先顺序是

  1. 从输入格式到JSON等输出格式的转换
  2. 转换速度应尽可能快。可以相应地选择编程语言。最好是js或python。也欢迎使用其他语言作为解决方案
  3. (可选)我们如何尽快将此解决方案扩展到1000秒的转换

Tags: 对象字符串json格式解决方案结构abcfield2
3条回答

如果准备了一个表示字段的数据结构,这些字段的名称和长度按顺序排列,则可以在字典理解中应用该结构,将数据拆分为各个键和值。然后使用json模块转换字典

from itertools import accumulate
import json

structure = [("field1",3),("field2",2),("field3",5)]      # define names and lengths
positions = [0,*accumulate(size for _,size in structure)] # computed starting positions

data      = "ABCDE12345"
dictdata  = { name:data[pos:pos+size] for (name,size),pos in zip(structure,positions) }
jsondata  = json.dumps(dictdata)

print(jsondata)
# {"field1": "ABC", "field2": "DE", "field3": "12345"}

你可以这样做:

&13; 第13部分,;
function strToObj(str, interface) {
  const outObj = {};
  let index = 0;

  Object.entries(interface).forEach(([key, value]) => {
    outObj[key] = str.slice(index, index + value);
    index = value
  });

  return JSON.stringify(outObj);
}

const testStr1 = 'ABCDE12345';
const testInterface1 = {
  key1: 3, // 'key1' will become the object key and 3 indicates the number of characters to use for the value
  key2: 4,
  key3: 3
}

const testStr2 = '+15417543010';
const testInterface2 = {
  intlPrefix: 2,
  localPrefix: 3,
  phonenumber: 7
}

console.log(strToObj(testStr1, testInterface1));
console.log(strToObj(testStr2, testInterface2));
和#13;
和#13;

或者简化版本,如果您不需要创建可重用函数

  1. 试试这个:

string_to_dict=lambda input_str:{“field1”:input_str[:3],“field2”:input_str[3:7], “field3”:输入[7:] 字符串到dict(“ABCDE12345”)

{'field1': 'ABC', 'field2': 'DE12', 'field3': '345'}

  1. 速度取决于您的输入源。如果您有熊猫数据帧,您可以通过使用“映射”功能将此功能应用于系列来最大化速度:

df['stinrg_series'].映射(字符串到dict)

相关问题 更多 >