1

I want this response: "socials": "Whatsapp_phone: 3413536723,Instagram: agusmac1,Linkedin: agusmac,Facebook: agusmac40"

to be something like:

 socials={
Whatsapp: 3413536723,
Instagram: agusmac1,
Linkedin: agusmac,
Facebook: agusmac20}

ive tried JSON parse but i cant make it work

3
  • can you share the code of your call and how you handle the response so we can better help you? Commented Oct 16, 2021 at 16:02
  • Who/what ever produces that response should be fired... Commented Oct 16, 2021 at 16:23
  • is this data coming from a restful API? if not what is the source, cause you can send a json object from a restful api directly so when you receive the response its already and object Commented Oct 16, 2021 at 16:49

1 Answer 1

2

You can first parse the string into an object by wrapping the string in curly braces and using JSON.parse.

Then, you can split the resulting object's socials property by a comma, split each individual item by a colon (with map), then use Object.fromEntries:

const str = `"socials": "Whatsapp_phone: 3413536723,Instagram: agusmac1,Linkedin: agusmac,Facebook: agusmac40"`

const obj = JSON.parse('{' + str + '}')
obj.socials = Object.fromEntries(obj.socials.split(",").map(e => e.split(":")))

console.log(obj)

If you want the value to be trimmed, you can use String.trim():

const str = `"socials": "Whatsapp_phone: 3413536723,Instagram: agusmac1,Linkedin: agusmac,Facebook: agusmac40"`

const obj = JSON.parse('{' + str + '}')
obj.socials = Object.fromEntries(obj.socials.split(",").map(e => (arr = e.split(":"), arr[1] = arr[1].trim(), arr)))

console.log(obj)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.