var string = 'job_category=IT^job_description=<p><span style="font-size: 18px;">Many other html attribute's </span></p>^job_type=2^qualification=2^EQ';
//oneline string to object starts here
function get_json_from_string(x) {
var ob = {};
var a = x.split("^");
for( i = 0 ; i < a.length ; i++){
var t = a[i].split('=');
ob[ t[0] ] = t[1];
}
return ob;
}
//oneline string to object ends here
var finalOutput = get_json_from_string(string);
console.log(finalOutput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我希望HTML能够从字符串中获取整个job_description,但是当我使用split时,它会打破upto =双引号。
我怎样才能正确分割?
预期结果对象的键值:
job_description:"<p><span style="font-size: 18px;">Many other html attributes </span></p>"
对象的当前结果键值:
job_description:"<p><span style="
//font-size: 18px;">Many other html attributes </span></p> this is cropping
注意请仔细检查我的字符串,它可以包含单引号和双引号
答案 0 :(得分:1)
您只想寻找第一个=
并忽略以下任何=
。
var string = 'job_category=IT^job_description=<p><span style="font-size: 18px;">Many other html attributes </span></p>^job_type=2^qualification=2^EQ'
//oneline string to object starts here
function get_json_from_string(x) {
var ob = {};
var a = x.split("^");
for( i = 0 ; i < a.length ; i++){
var eq = a[i].indexOf('=')
if(eq==-1){
//no = in this part... handle it yourself
continue;
}
var key = a[i].slice(0,eq)
var value = a[i].slice(eq+1)
ob[ key ] = value;
}
return ob;
}
//oneline string to object ends here
var finalOutput = get_json_from_string(string);
console.log(finalOutput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 1 :(得分:1)
您可以拆分'^',然后拆分'=',将第一个元素作为键,然后将其余部分加上'='作为值。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
services-cloud-init:
type: OS::Heat::CloudConfig
properties:
cloud_config:
timezone: {get_param: time_zone}
write_files:
- path: /tmp/change_password.sh
owner: root:root
permissions: '0777'
content: |
#!/bin/bash
echo -e "pwd\npwd" | passwd cloud-user
- path: /run/change_timezone.sh
owner: root:root
permissions: '0777'
content: |
#!/bin/bash
ln -sf /usr/share/zoneinfo/timezone /etc/localtime
runcmd:
- echo "Executing change_timezone"
- /tmp/change_timezone.sh
- echo "Executing change_password"
- /tmp/change_password.sh
- reboot
bootcmd:
- echo "Boot Completed"
答案 2 :(得分:-1)
在值"<p><span style="font-size: 18px;">Many other html attributes </span></p>"
的JSON对象中,使用单引号(... style ='font-size:18px;'...)而不是双引号。