Hướng dẫn replace string in json python - thay thế chuỗi trong json python

Tôi chưa quen với Python và những gì tôi đang cố gắng làm là thay thế văn bản/chuỗi trong tệp JSON, từ lệnh shell os python. Tôi có phần nhận được kết quả mà tôi đang tìm kiếm, nhưng nó đang nối thêm khoảng trắng/tạo một dòng mới trong tệp JSON. Đây về cơ bản là những gì tôi đang cố gắng thực hiện:

  1. Tôi có một tệp JSON tĩnh (add.json)
  2. Tôi đang chạy hai lệnh os shell trong Python và lưu trữ đầu ra đó vào các tệp văn bản riêng biệt.
  3. Sau đó tôi muốn lấy các giá trị trong hai tệp TXT đó và thay thế hai chuỗi trong tệp JSON.

Dưới đây là những gì tôi hiện có (để làm cho nó đơn giản, tôi đã thay thế các lệnh AWS CLI thực sự bằng các lệnh đơn giản)

import os
import fileinput

cmd = 'hostname > host.txt'
cmd2 = 'echo mama > echo.txt'

os.system(cmd)
os.system(cmd2)

file = open('host.txt')
contents = file.read()
with open("out.json", "wt") as fout:
with open("add.json", "rt") as fin:
    for line in fin:
        fout.write(line.replace('dns',contents))

file2 = open('echo.txt')
contents2 = file2.read()
with open("out2.json", "wt") as fout2:
    with open("out.json", "rt") as fin2:
    for line in fin2:
        fout2.write(line.replace('ip', contents2))

Và đây là kết quả mà nó mang lại:

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}

Như bạn có thể thấy, sau tên và giá trị, nó thực sự thay thế các giá trị, nhưng thêm một dòng mới và tạo ra JSON không hợp lệ.

Đây là tệp tôi thay thế các giá trị trong:

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}

Cảm ơn bạn trước cho bất kỳ câu trả lời. Tôi biết những gì tôi có ở trên là rất bẩn, và tôi chắc chắn rằng phải có một cách tốt hơn/sạch hơn để hoàn thành những gì tôi đang cố gắng làm, nhưng cuối cùng tôi biết tất cả chúng ta phải bắt đầu ở đâu đó và tôi thậm chí không thể bắt đầu Để giải thích tôi biết ơn như thế nào với cộng đồng này vì tất cả sự giúp đỡ mà nó được cung cấp cho đến nay.

Vì vậy, đây là JSON:

{
    "template_name": "template1",
    "ch2": {
        "textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
        "bigskip": "My first cookbook"
    }
}

Và khi tôi cố gắng truy cập nó với mã này:

directory = str(uuid.uuid4())
parent_dir = "C:\PycharmProjects\pythonProject"
src = "C:\PycharmProjects\pythonProject\Template"
path = os.path.join(parent_dir, directory)
destination = shutil.copytree(src, directory)


with open("C:\PycharmProjects\pythonProject\\test.json") as f:
    data = json.load(f)

with open(f"C:\PycharmProjects\pythonProject\\Template\\body\ch2.tex", 'r')as f:
    text = f.read()

    for key, value in data.items():
        text = text.replace('{'+key+'}', value)

with open(f"C:\PycharmProjects\pythonProject\\{destination}\\body\ch2.tex", "w")as out:
    out.write(text)

Nó trả về lỗi sau:

Traceback (cuộc gọi gần đây nhất cuối cùng):

Tệp "uuid-test.py", dòng 21, trong

text = text.replace ('{'+key+'}', value)

TypeError: thay thế () đối số 2 phải là str, không phải dict

Nếu có ai có thể giúp tôi sẽ rất biết ơn

Cảm ơn bạn trước!

Sau đây là 30 ví dụ mã của String.replace (). Bạn có thể bỏ phiếu cho những người bạn thích hoặc bỏ phiếu cho những người bạn không thích và đi đến dự án gốc hoặc tệp nguồn bằng cách theo các liên kết trên mỗi ví dụ. Bạn cũng có thể muốn kiểm tra tất cả các chức năng/lớp có sẵn của chuỗi mô -đun hoặc thử chức năng tìm kiếm.30 code examples of string.replace(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string, or try the search function

Hướng dẫn replace string in json python - thay thế chuỗi trong json python
.

Ví dụ 1

def getIndex(form, pos='noun'):
    """Search for _form_ in the index file corresponding to
    _pos_. getIndex applies to _form_ an algorithm that replaces
    underscores with hyphens, hyphens with underscores, removes
    hyphens and underscores, and removes periods in an attempt to find
    a form of the string that is an exact match for an entry in the
    index file corresponding to _pos_.  getWord() is called on each
    transformed string until a match is found or all the different
    strings have been tried. It returns a Word or None."""
    def trySubstitutions(trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor(pos)):
        if lookup and dictionary.has_key(form):
            return dictionary[form]
        elif substitutions:
            (old, new) = substitutions[0]
            substitute = string.replace(form, old, new) and substitute != form
            if substitute and dictionary.has_key(substitute):
                return dictionary[substitute]
            return              trySubstitutions(trySubstitutions, form, substitutions[1:], lookup=0) or \
                (substitute and trySubstitutions(trySubstitutions, substitute, substitutions[1:]))
    return trySubstitutions(returnMatch, form, GET_INDEX_SUBSTITUTIONS) 

Ví dụ #2

def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 

Ví dụ #3

def getIndex(form, pos='noun'):
    """Search for _form_ in the index file corresponding to
    _pos_. getIndex applies to _form_ an algorithm that replaces
    underscores with hyphens, hyphens with underscores, removes
    hyphens and underscores, and removes periods in an attempt to find
    a form of the string that is an exact match for an entry in the
    index file corresponding to _pos_.  getWord() is called on each
    transformed string until a match is found or all the different
    strings have been tried. It returns a Word or None."""
    def trySubstitutions(trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor(pos)):
        if lookup and dictionary.has_key(form):
            return dictionary[form]
        elif substitutions:
            (old, new) = substitutions[0]
            substitute = string.replace(form, old, new) and substitute != form
            if substitute and dictionary.has_key(substitute):
                return dictionary[substitute]
            return              trySubstitutions(trySubstitutions, form, substitutions[1:], lookup=0) or \
                (substitute and trySubstitutions(trySubstitutions, substitute, substitutions[1:]))
    return trySubstitutions(returnMatch, form, GET_INDEX_SUBSTITUTIONS) 

Ví dụ #4

def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 

Ví dụ #5

def main():
    print "This program converts a textual message into a sequence"
    print "of numbers representing the ASCII encoding of the message."
    print
    
    # Get the message to encode
    message = raw_input("Please enter the message to encode: ")
    n = int(raw_input("Enter the key value"))
    print
    print "Here are the ASCII codes:"
    z = string.replace(message,"z","a")
    z1 = string.replace(z,"Z","A")
    
    # Loop through the message and print out the ASCII values
    for ch in z1:
        a = chr(ord(ch) + n),   # use comma to print all on one line.
        print " ".join(a),
    print 

Ví dụ #6

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
0

Ví dụ #7

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
1

Ví dụ #8

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
2

Ví dụ #9

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
3

Ví dụ #10

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
4

Ví dụ #11

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
5

Ví dụ #12

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
6

Ví dụ #13

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
7

Ví dụ #14

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
8

Ví dụ #15

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
9

Ví dụ #16

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
0

Ví dụ #17

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
1

Ví dụ #18

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
2

Ví dụ #19

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
3

Ví dụ #20

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
4

Ví dụ #21

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
5

Ví dụ #22

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
8

Ví dụ #23

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "WildburritoPC
 ",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "mama 
"
      }
     ]
   }
  }
 ]
}
9

Ví dụ #24

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
0

Ví dụ #25

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
1

Ví dụ #26

{
"Comment": "A new record set for the zone.",
"Changes": [
 {
  "Action": "CREATE",
  "ResourceRecordSet": {
    "Name": "dns",
    "Type": "A",
    "TTL": 60,
    "ResourceRecords": [
      {
        "Value": "ip"
      }
    ]
   }
  }
 ]
}
2

Ví dụ #27

{
    "template_name": "template1",
    "ch2": {
        "textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
        "bigskip": "My first cookbook"
    }
}
1

Ví dụ #28

{
    "template_name": "template1",
    "ch2": {
        "textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
        "bigskip": "My first cookbook"
    }
}
2

Ví dụ #29

{
    "template_name": "template1",
    "ch2": {
        "textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
        "bigskip": "My first cookbook"
    }
}
3

Ví dụ #30

{
    "template_name": "template1",
    "ch2": {
        "textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
        "bigskip": "My first cookbook"
    }
}
1

Làm cách nào để thay thế một giá trị trong tệp JSON bằng Python?

Đối với mọi dòng, bạn có thể sử dụng Regex để tìm và thay thế. Sau đó, bạn có thể ghi đè tệp hoặc ghi vào một tệp mới. Ngoài ra, bạn có thể tải python json vào và chuyển đổi nó thành một chuỗi. Sau đó thay thế văn bản bằng regex.use regex to find and replace. Then you can either overwrite the file or write onto a new file. Alternatively, you can load the json python in and convert it into a string. Then replace the text using the regex.

Làm thế nào để bạn cập nhật chuỗi JSON trong Python?

Việc cập nhật một đối tượng JSON trong Python cũng đơn giản như sử dụng chức năng Cập nhật () tích hợp từ gói JSON mà chúng tôi đã nhập.Phương thức cập nhật được sử dụng để thêm một cặp giá trị khóa mới vào chuỗi JSON mà chúng tôi đã khai báo trong mã của chúng tôi.using the built-in update() function from the json package we have imported. The update method is used to add a new key-value pair to the JSON string that we declared in our code.

Làm cách nào để thay đổi văn bản trong tệp JSON?

Làm cách nào để thay đổi văn bản trong tệp JSON ?..
với mở ('file.json', 'r+') dưới dạng tệp:.
Nội dung = Tệp.đọc().
tập tin.tìm kiếm (0).
Nội dung.thay thế ('String_Replace', 'New_String').
tập tin.Viết (nội dung).

Làm cách nào để thay thế một chuỗi trong một chuỗi trong Python?

thay thế () phương thức trả về một bản sao của một chuỗi ...
old_text là tham số bắt buộc đầu tiên.thay thế () chấp nhận.Đó là nhân vật hoặc văn bản cũ mà bạn muốn thay thế.....
new_text là tham số cần thiết thứ hai.thay thế () chấp nhận.....
Đếm là tham số thứ ba tùy chọn đó.thay thế () chấp nhận ..